views:

1142

answers:

6

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.

+4  A: 

No, for that you should use protected.

RichieHindle
Actually, you should use a protected setter in case the private variable is removed from a future version of the class.
jmucchiello
+1  A: 

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

+2  A: 

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.

Sandro
+1  A: 

...if there is no accessor method defined in foo?

You need accessors. Besides, take care of inheritance, Should that var really be in parent? Remember IS-A check..

ktulur
+2  A: 

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);
Wim Coenen
+1  A: 

You cannot access private variables in descendent classes. Normally you'd want to use "protected" or "package" (the default) level access for this. However if you want to be really tricky, you can resort to using reflection and AccessibleObject to get at it. I wouldn't recommend doing that for production code unless you are really in a bind; for testing, etc., it's fine.

Caffeine Coma