Accessing private instance variables of parent from child class?

81,015

Solution 1

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);

Solution 2

No, for that you should use protected.

Solution 3

For questions like this, where is a table found on the website here: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

Basically you want public or protected variable to be declared in foo since these are the variables that subclasses inherit from their parent and therefore seen in baz.

Solution 4

To use a private variable of a super class in a sub class, an accessor method is required. Else use the protected modifier instead of private.

Solution 5

Child classes can not access private members (which is the whole point of private access control).

Share:
81,015
Elyas Behroozizade
Author by

Elyas Behroozizade

I was a ♦ on Ubuntu StackExchange. More broadly, I'm an Ubuntu and Debian Developer. See my Launchpad profile.

Updated on July 15, 2021

Comments

  • Elyas Behroozizade
    Elyas Behroozizade almost 3 years

    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.

  • jmucchiello
    jmucchiello almost 15 years
    Actually, you should use a protected setter in case the private variable is removed from a future version of the class.
  • sdfsdf
    sdfsdf over 6 years
    use can protected on instance variables
  • Steve Moretz
    Steve Moretz about 5 years
    Super just added a function to a library using your workaround.
  • John Humphreys
    John Humphreys almost 5 years
    Thanks @Wim. Here's an example with full classes based on this if someone wants to just copy paste to test: coding-stream-of-consciousness.com/2019/06/11/….
  • Andreas
    Andreas about 4 years
    Caveat: You can access private members of the super class if both super class and subclass are within scope of the same top-level class.