I'm trying to understand the concepts of polymorphism and overloading. I have the following code as a sort of experiment. I cannot figure out, however, why this program does not run (it fails because of mobj.foo(str)
. mobj
is defined using polymorphism, and from what I can gather, should be of type MyDerivedClass
. If that were true though, wouldn't the line in question work fine?
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());
}
}
its failing because of
MyBaseClass mobj = new MyDerivedClass();
you told the compiler that mobj is a MyBaseClass, so it doesn't know that there is a foo(String) method.
That sort of thing gets resolved at runtime.
Polymorphism only works when you are overriding a method that the parent has already defined, which is not the case with mobj.foo(str)
. MyBaseClass
does not implement a class with signature foo(String)
. So foo(String)
implemented in MyDerivedClass
is not overriding anything. Remember java distinguishes methods by name and parameters.
mobj
is an instance of MyDerivedClass
, but of type MyBaseClass
. So you can call only the methods defined for MyBaseClass
on mobj
. That's why mobj.foo(str)
fails.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.