The issue of polymorphism and overload

I am trying to understand the concepts of polymorphism and overload. I have the following code as a kind of experiment. However, I can’t understand why this program does not start (it fails because of mobj.foo(str). Is mobjdetermined using polymorphism, and from what I can assemble, it should be like MyDerivedClass. If this was true, though, would this line not work fine?

Why is this line invalid?

class MyBaseClass {
  protected int val;
  public MyBaseClass() { val = 1; }
  public void foo() { val += 2; }
  public void foo(int i) { val += 3; }
  public int getVal() { return val; }
}

class MyDerivedClass extends MyBaseClass {
  public MyDerivedClass () { val = 4; }
  public void foo() { val += 5; }
  public void foo(String str) { val += 6; }
}

class Test {
  public static void main(String[] args)
  {
    MyBaseClass mobj = new MyDerivedClass();
    String str = new String("hello");
    mobj.foo();
    mobj.foo(str);
    mobj.foo(4);
    System.out.println("val = " + mobj.getVal());
  }
}
+3
source share
3 answers

, , , mobj.foo(str). MyBaseClass foo(String). , foo(String), MyDerivedClass, . , java .

+3

-

 MyBaseClass mobj = new MyDerivedClass();

, mobj - MyBaseClass, , foo (String).

.

+7

mobj MyDerivedClass, MyBaseClass. , , MyBaseClass mobj. mobj.foo(str) .

+2

Source: https://habr.com/ru/post/1770611/


All Articles