Note that there are some explanatory texts on larger screens.

plurals
  1. POHiding instance variables of a class
    text
    copied!<p>I'm wondering why Java has this strange behavior regarding a superclass and a subclass having instance variables with the same name.</p> <p>Let's say we have the following class definitions:</p> <pre><code>class Parent { int var = 1; } class Child extends Parent { int var = 2; } </code></pre> <p>By doing this, we are supposed to have hidden the superclass's variable <code>var</code>. And if we do not explicitly specify a way to access <code>Parent</code>'s <code>var</code> via a <code>super</code> call, then we should never be able to access <code>var</code> from an instance of a child.</p> <p>But when we have a cast, this hiding mechanism breaks:</p> <pre><code>Child child = new Child(); Parent parent = (Parent)child; System.out.println(parent.var); // prints out 1, instead of 2 </code></pre> <p>Doesn't this completely circumvent the whole point of field hiding? If this is the case, then doesn't that render the the idea completely useless?</p> <p><strong>EDIT</strong>: I am referring specifically to <a href="http://download.oracle.com/javase/tutorial/java/IandI/hidevariables.html">this article</a> in the Java Tutorials. It mentions</p> <blockquote> <p>Within the subclass, the field in the superclass <strong>cannot</strong> be referenced by its simple name. Instead, the field <strong>must</strong> be accessed through super...</p> </blockquote> <p>From what I read there, it seems to imply that the developers of Java had some kind of technique in mind in doing this. Though I agree that it is a rather obscure concept and would probably bad practice in general.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload