Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about polymorphism and overloading

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());
  }
}
like image 644
dfetter88 Avatar asked Sep 02 '26 13:09

dfetter88


2 Answers

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.

like image 163
hvgotcodes Avatar answered Sep 04 '26 03:09

hvgotcodes


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.

like image 32
shoebox639 Avatar answered Sep 04 '26 03:09

shoebox639



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!