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
A subclass does not inherit the private members of its parent class.
However, I find it more useful to think of it as
A subclass inherits the private members of its parent class but does not have access to them
but this boils down to sematics.