Polymorphism with instance variables

Here are three classes that I wrote:

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());
    }
}

Exiting the main method of the Tester class:

I am a rectangle!

1

I am a rectangle!

L * w

0

1

Why does sx return 0, not 1? As not the current instance of the Rectangle variable, and this class also has the same instance variable, or the variable in the Rectangle class does not override the previous public variable x in the Shape class, as for getX (), the method in the rectangle class, thus returning 1?

In addition, as a rule, does a superclass have access to the implementation of its subclasses only if they are declared in this class? Is this because the compiler will see that the same number of methods with the same signature are in the Shape class (with overridden Rectangle implementations) and accepts them as valid Shape methods?

,

+5
2

Java . . Rectangle . , :

public class Rectangle {
    public int Shape.x;
    public int Rectangle.x;
}

Java, ,

Rectangle . , x this.x, , Rectangle. , super.x.

- , , . , . , :

Shape s = new Shape();
Rectangle r = new Rectangle();

s = r;
System.out.println(s.x);

0, s Shape ( Rectangle). , :

Shape s = new Shape();
Rectangle r = new Rectangle();

s = r;
System.out.println(((Rectangle)s).x);

Presto! 1, , Rectangle.

:

JLS, 8.3.3.2

+13

, . , x 1, . , , . , public ! , , , , .

0

All Articles