Here's an interesting code snippet:
public class Superclass {
public static void main (String[] args){
Superclass obj = new Subclass();
obj.doSomething(); #prints "from Superclass"
}
private void doSomething(){System.out.println("from Superclass");}
}
class Subclass extends Superclass {
private void doSomething(){System.out.println("from Subclass");}
}
I know that subclasses do not inherit the private members of its parent, but here obj manages to call a method to which it should have no access. At compile time obj is of type Superclass, at runtime of type Subclass.
This probably has something to do with the fact that the call to doSomething() is taking place inside the driver class, which happens to be its own class (and why it's possible to invoke doSomething() in the first place).
So the question boils down to, how does obj have access to a private member of its parent?
private methods are not inherited. A does not have a public say() method therefore this program should not compile.
Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
But, if you inherit a class that has private fields, including all other members of the class the private variables are also inherited and available for the subclass. But, you cannot access them directly, if you do so a compile-time error will be generated.
A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
You answered it yourself. As the private methods are not inherited, a superclass reference calls its own private method.
Private methods are only for the owner.
Not even for the kids, relatives or friends of the owner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With