Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is no polymorphism for fields in Java. There is however, inheritance. What you've effectively done is create two fields in your Rectangle class, with the same name. The names of the field are, effectively:</p> <pre><code>public class Rectangle { public int Shape.x; public int Rectangle.x; } </code></pre> <p><em>The above doesn't represent valid Java, its just an illustration of how the fields are scoped in your class</em></p> <p>Within the entire scope of the Rectangle class, the superclass field of the same name is <em>hidden</em>. So anytime you reference the simple name <code>x</code>, or the scoped name <code>this.x</code>, within the class, you are referring to the field that is defined in <code>Rectangle</code>. You can actually access the superclass field as well, with the scoped name <code>super.x</code>.</p> <p>Now, from outside of the class, the rules for which field is being accessed is slightly different. The scope will be determined by the <strong><em>compile</em></strong> time type of the class that the field is being referenced from. So in your code:</p> <pre><code>Shape s = new Shape(); Rectangle r = new Rectangle(); s = r; System.out.println(s.x); </code></pre> <p>The output is <code>0</code> because the compile time type of <code>s</code> is <code>Shape</code> (not <code>Rectangle</code>). You can observe a change in this behavior when you do this:</p> <pre><code>Shape s = new Shape(); Rectangle r = new Rectangle(); s = r; System.out.println(((Rectangle)s).x); </code></pre> <p>Presto! Your output is now <code>1</code>, because the compiler sees that you've scoped the field access to <code>Rectangle</code>.</p> <p>To condense the rules of visibility:</p> <p>You can read more about instance variable hiding in the <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.3.3.2" rel="noreferrer">JLS, Section 8.3.3.2</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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