Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a private variable in a inherited class - Java

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.?

like image 812
Kannan Ramamoorthy Avatar asked Mar 21 '13 14:03

Kannan Ramamoorthy


People also ask

Can we use private variables in inheritance?

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.

Can inherited classes access private methods?

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.

Can we use private variable in another class Java?

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.

Do private attributes get inherited Java?

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.


2 Answers

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.

like image 102
Sudhanshu Umalkar Avatar answered Nov 14 '22 23:11

Sudhanshu Umalkar


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.

like image 23
Evgeniy Dorofeev Avatar answered Nov 14 '22 22:11

Evgeniy Dorofeev