Java 理解继承:getter 和 setter 来自 parents class

Java understanding inheritance: getter and setter from parents class

Java又是初学者。我试图了解继承是如何工作的,我想我有点明白了,但我的代码没有按我预期的那样工作,而且很难找出原因。

问题是我的 getter 和 setter 方法来自 parent 的 class。我的代码似乎没有像我预期的那样调用它们。

这是我的 parent class:

class MyPoint {
    public int x, y;

    MyPoint() {
        x = 0;
        y = 0;
    }

    MyPoint(int x, int y) {
        this.x = x;
        this.y = y;
    }

    MyPoint(MyPoint myPoint) {
        x = myPoint.x;
        y = myPoint.y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setX(int x) {
        if (x > 0) {
            this.x = x;
        }
    }

    public void setY(int y) {
        if (y > 0) {
            this.y = y;
        }
    }

    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

和 child class:

class MySubLine extends MyPoint {
    int x, y, x1, y1;
    MyPoint endPoint;

    public MySubLine() {
        super();
        x1 = 0;
        y1 = 0;
    }

    public MySubLine(int x, int y, int x1, int y1) {
        super(x, y);
        this.x = x;
        this.y = y;
        this.x1 = x1;
        this.y1 = y1;
    }

    public MySubLine(MyPoint p1, MyPoint p2) {
        super(p1.x, p1.y);
        x = p1.x;
        y = p2.y;
        x1 = p2.x;
        y1 = p2.y;
    }

    public int getEndX() {
        return x1;
    }

    public int getEndY() {
        return y1;
    }

    public void setEndX(int x) {
        if (x > 0) {
            this.x1 = x;
        }
    }

    public void setEndY(int y) {
        if (y > 0) {
            this.y1 = y;
        }
    }

    public double getLength() {
        return Math.sqrt(Math.pow((x1 - x), 2) + Math.pow((y1 - y), 2));
    }

    public String toString() {
        return "(" + x + ", " + y + ") to (" + x1 + ", " + y1 + ")";
    }
}

当我尝试运行一个

的测试用例时
MySubLine line = new MySubLine();
line.setX(40); line.setY(50);
System.out.println(line);

在我的主 Java 文件中,我得到的结果是 (0, 0) to (0, 0) 而预期结果是 (40, 50) to (0, 0).

为什么我的 setter 方法没有被触发?

任何帮助将不胜感激!

您在子class中再次声明了 x 和 y,因此它们遮盖了超 class

中具有相同名称的变量
line.setX(40)

这将调用 superclass 中的方法,从而在 MyPoint

中设置 x

中子class

public String toString() {
    return "(" + x + ", " + y + ") to (" + x1 + ", " + y1 + ")";
}

这将访问 MySubLine 中尚未修改的 x 和 y。

解决方案:从 MySubLine

中删除作为实例成员的 x 和 y