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