I read <thinking in java>, the output of this code is "private f()"
the book does not explain well.
my understanding is :
derived class and base class has identical f() method, but derived one does not override base one.
so when po.f() is called, it should still goes to the derived class' method ,
which should output "public f()"
BUT why is that incorrect?
when you use private modifier to method/variable then it is visible only in that class in which they are declared. In your case you have method private void f() in Parent class. This method is not visible to Subclass. If Subclass doesn't even know that void f() method is exist. Then How it will ovverride this method? Therefore when you run this program then Parent class method is invoked.
If suppose you fave another method as public void f1() as
Now subclass version of method is invoked and you get output as
Life is easy because we write the source code.....
Joined: Nov 15, 2009
Mohamed Sanaulla wrote:Your reference type is of Base class. So it would invoke the Base class method.
what about dynamic binding, in runtime, the app should execuete the acutal object (not reference object)'s method, which is 'public f()'
The general rule here is this, when you use a super class as a reference type and subtype as the object, you can only invoke methods that are COMMON to both classes. If the method was overridden by the subtype then at run time the subtype method is the one that runs.
Sub Classes have NO KNOWLEDGE of private methods in their super classes. If both classes have no methods common to them, then the super type reference invokes the method in it's own class. (The Devil you know is better than the Angel you don't know!)