Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private instance variables of parent from child class?

Let's say we have a class foo which has a private instance variable bar.

Now let us have another class, baz, which extends foo. Can non-static methods in baz access foo's variable bar if there is no accessor method defined in foo?

I'm working in Java, by the way.

like image 747
lfaraone Avatar asked May 04 '09 23:05

lfaraone


People also ask

Can a child class access private variable of parent class?

Inheritance means that an object of the child class automatically includes the object fields and methods defined in the parent class. But, if the inherited fields are private, which they should be, the child class can not directly access the inherited fields using dot notation.

How do you access the private variable of parent class in a child class python?

Use a single underscore ( _field ) instead. This "documents" that the attribute is intended to be private (e.g. not part of a class's public API), without enabling name mangling. That way, if you find later than another class does need to access the variable it can.

How do you access private members of parent class?

A class in C++ has public, private and protected sections which contain the corresponding class members. Protected members in a class are similar to private members as they cannot be accessed from outside the class. But they can be accessed by derived classes or child classes while private members cannot.

Do child classes inherit private instance variables?

Subclasses inherit public methods from the superclass that they extend, but they cannot access the private instance variables of the superclass directly and must use the public accessor and mutator methods.


2 Answers

No, not according to the java language specification, 3rd edition:

6.6.8 Example: private Fields, Methods, and Constructors

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses.

But regardless of this language restriction, you can access private fields through reflection:

Field privateStringField =     MyClass.class.getDeclaredField("privateString"); privateStringField.setAccessible(true);  String fieldValue = (String) privateStringField.get(privateObject); System.out.println("fieldValue = " + fieldValue); 
like image 127
Wim Coenen Avatar answered Sep 23 '22 17:09

Wim Coenen


No, for that you should use protected.

like image 26
RichieHindle Avatar answered Sep 20 '22 17:09

RichieHindle