I have read that a subclass cannot inherit private fields or methods. However, in this example
class SuperClass {
private int n=3;
int getN() {
return n;
}
}
class SubClass extends SuperClass {
public static void main(String[] args) {
SubClass e = new SubClass();
System.out.println("n= " + e.getN());
}
}
When I run main I get the output as n=3. Which seems that SubClass is inheriting the private attribute n from SuperClass.
So, please explain what’s going on here. Thank you.
The subclass ‘has’ the fields of its superclass, but does not have access to them directly. Similarly, the subclass ‘has’ the private methods, but you cannot call or override them from the subclass directly.
In the Java documentation on inheritance, it says that
However, I find it more useful to think of it as
but this boils down to sematics.