Private members and inheritance
I read in the tutorial that class members marked as private are not inherited. So I thought that if the class A
has a variable private
x
, and the class B
will extend the class A
, then B
there will be no variable in the class x
. However, the following example shows that I misunderstood that:
public class testdrive
{
public static void main(String[] args) {
B b = new B();
b.setLength(32);
System.out.print(b.getLength());
}
}
class A {
private int length;
public void setLength(int len) {
length = len;
}
public int getLength() {
return length;
}
}
class B extends A {
public void dummy() {
}
}
The result is 32 and I am confused because it looks like an object with ref B
now has a variable length
and its value is 32. But ref B
refers to an object created from a class B
where the variable length
is undefined. So, what's true, the class B
inherits a variable private
length
? If so, what does it mean that variables are private
not inherited?
source to share
Hey don't you think private fields can only be accessed by methods present in one class (given that methods are accessible from another class)
its not something you can call directly:
b.length=8;
Or you can't even do this: (write this when you created an object for B)
A a = new A();
a.length=8;
both of these approaches are invalid!
For more information:
you don't even need to extend B from A, just create an object A basically and use these get and set methods and it will work too!
source to share
You do not have direct access to the private fields and superclass method, but you can access them using other public methods.
This is one of the fundamental concepts of object-oriented programming and is called Encapsulation . More on this here: TutorialsPoint .
Bottom line : you cannot directly access a private field or method like this
b.length = 32;
and don't like (for superclass)
A a = new A();
a.length = 32;
but you can manipulate these fields with a public method like in your example.
The reason is simple: your private fields / methods are hidden to other classes except for the class that contains them , but your public fields / methods are not hidden.
source to share