Need to have more understanding about the private variables and inheritance. Earlier my understanding was if there is field in a class and when I'm inheriting the class, the fields that is not restricted by access(private variables) will be there in the inherited class. But I'm able use the private variables in base class if there is a public g/setter method.
How can I imagine a private variable in a base class.?
Private Members in a SuperclassA subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
Private methods are inherited in sub class ,which means private methods are available in child class but they are not accessible from child class,because here we have to remember the concept of availability and accessibility.
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.
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. The answer is No. They do not.
private variables / members are not inherited. That's the only answer.
Providing public accessor methods is the way encapsulation works. You make your data private and provide methods to get or set their values, so that the access can be controlled.
This is what Java tutorial http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html says:
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
Nevertheless, see this
class A {
private int i;
}
class B extends A {
}
B b = new B();
Field f = A.class.getDeclaredField("i");
f.setAccessible(true);
int i = (int)f.get(b);
it works fine and returns value of field i
from B instance. That is, B has i
.
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