Note that there are some explanatory texts on larger screens.

plurals
  1. POPolymorphism with instance variables
    text
    copied!<p>Here are three classes that I wrote:</p> <pre><code>public class Shape { public int x = 0; public void getArea() { System.out.println("I don't know my area!"); } public String toString() { return "I am a shape!"; } public int getX() { return x; } } public class Rectangle extends Shape { public int x = 1; public int getX() { return x; } public void getArea() { System.out.println("L*W"); } public String toString() { return "I am a rectangle!"; } } public class Tester { public static void main(String[] args) { Shape s = new Shape(); Rectangle r = new Rectangle(); System.out.println(r); System.out.println(r.x + "\n"); s = r; System.out.println(s); s.getArea(); System.out.println(s.x); System.out.println(s.getX()); } } </code></pre> <p>The output from the main method of the Tester class is: </p> <pre> I am a rectangle! 1 I am a rectangle! L*W 0 1 </pre> <p>Why does s.x return 0 and not 1? As isn't the current instance of the variable a Rectangle and that class also has that same instance variable declared, or does the variable in the Rectangle class not override the previous public x variable in the Shape class as it does to the getX() method in the rectangle class thus returning 1?</p> <p>Also as a general rule the superclass has access to the implementation of the its subclasses methods only if they are declared in that class as well? Is this because the compiler will see that the same amount of methods with the same signature are in the "Shape" class (with overridden Rectangle implementations) and accept those as valid Shape methods?</p> <p>Thanks in advance,</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