views:

72

answers:

3

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

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.

hvgotcodes
+2  A: 

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.

MicSim
+3  A: 

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.

shoebox639
Thanks. This makes sense.
dfetter88