override - Overriding vs Overloading in JAVA inheritance -


give code:

class foo{     public string tostring(foo foo){return " foo";}      public void printme(){system.out.print(this.tostring(this));} }  class bar extends foo{             public string tostring(bar bar){return " bar";} }  class myclass{     foo foo = new foo();     bar bar = new bar();     foo baz = new bar();      public static void main(string[] args){         myclass m = new myclass();         m.foo.printme();         m.bar.printme();         m.baz.printme();     } } 

output is:

foo foo foo 

please, explain why it's not called bar.tostring() through bar-reference?

it because jvm first check method binding in subclass if not found check in superclass.

1) foo foo = new foo(); 

foo has printme()

2) bar bar = new bar(); 

bar not have printme() jvm call foo's method

3) foo baz = new bar(); 

bar not have printme() jvm call foo's method

and in printme() method call foo's tostring() method.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -