Vivek Raj wrote:
In the above code doStuff() is private in Super. But main method is in the class Super and the ref variable 's' is also of type Super, so compiler sees this as perfect method invocation.
However as per K&B instance method invocation is virtual and happens at run-time based on the actual object the ref variable is holding (Sub object in this case) and Sub has not inherited the private method from Super.
But still its calling the private method and printing "In Super". How is this happening?
Dynamic call to a method only occur when the methods are overridden. Methods with access modifier private can never be overidden. In your code, the method invocation does not follow the dynamic invocation rule of method override, hence the type of the reference variable i.e Super decide which method signature will be invoked, in your case, it is the doStuff() in Super class.