Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, why can't a super-class method access protected or private methods/variables from a sub-class instance?

Let's start with another behavior: even if you declare a method/variable as private, another instance of the same class can access it. That's OK I can live with it. I call these class-private and not instance-private.

Now the question part: For example, at runtime I want to be able to check that all String variables in this class are not null, and if they are null they should be changed to the string "NULL".

I can run through the variables using reflection and get their values. But if I extend my class and add private or even protected variables my base class can't access them. I have to setAccessible on the variables before I can use them.

So please explain to me why the base-class (super-class) can't access private/protected variables from its sub-class. It is its sub-class, so I don't get it. What's the idea behind this?

I know that the super-class should not know about its sub-classes, but in my example it makes sense, no?

Is it because I can't or shouldn't restrict my sub-classes in this way?


Update: Based on the answers, I want to know also: Why isn't accessing another instance's private variables from the same class considered a violation of encapsulation?

like image 451
m_vitaly Avatar asked May 22 '09 18:05

m_vitaly


People also ask

Can subclasses access private variables of super class Java?

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.

Can subclass access private methods of super class?

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. A nested class has access to all the private members of its enclosing class—both fields and methods.

Can we access private method using super?

We can't access private methods of a superclass with a sub class reference. See "ref" is the Superclass Reference But it contains Subclass Object. So by using Superclass Refernce only we can access the Private Method.


1 Answers

It's as simple as it's a violation of encapsulation. Another class should not be able to reach into your class and be messing around with things, even if you generalize that class. How does a Vehicle know anything about a Car for example? The whole point of a base class is to provide for the sub-classes, but like an over-protective parent, what you're suggesting would be too much.

like image 106
JP Alioto Avatar answered Oct 12 '22 23:10

JP Alioto