Accessing private instance variables of parent from child class?
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).
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, 2021Comments
-
Elyas Behroozizade almost 3 years
Let's say we have a class
foo
which has a private instance variablebar
.Now let us have another class,
baz
, whichextends foo
. Can non-static methods inbaz
accessfoo
's variablebar
if there is no accessor method defined infoo
?I'm working in Java, by the way.
-
jmucchiello almost 15 yearsActually, you should use a protected setter in case the private variable is removed from a future version of the class.
-
sdfsdf over 6 yearsuse can protected on instance variables
-
Steve Moretz about 5 yearsSuper just added a function to a library using your workaround.
-
John Humphreys almost 5 yearsThanks @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 about 4 yearsCaveat: You can access
private
members of the super class if both super class and subclass are within scope of the same top-level class.