Java – questions about polymorphism and overloading

I try to understand the concepts of polymorphism and overloading I have the following code as an experiment However, I can't figure out why the program didn't run (it failed because of mobj. Foo (STR)) Use polymorphism to define mobj, and from the content I can collect, it should be myderivedclass type If this is true, will this line not work properly?

Why is that 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());
  }
}

Solution

Polymorphism is only valid when overriding methods defined by the parent, and mobj Foo (STR) is not Mybaseclass does not implement a class with a signature foo (string) So foo (string) implemented in myderivedclass does not cover anything Remember that Java distinguishes methods by name and parameter

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>