【问题标题】:Java understanding inheritance: getter and setter from parents classJava理解继承:父类的getter和setter
【发布时间】:2020-04-10 13:14:20
【问题描述】:

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

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

这是我的父类:

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 + ")";
    }
}

还有子类:

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 方法没有触发?

任何帮助将不胜感激!

【问题讨论】:

  • 尝试改变 int x, y, x1, y1;到只是 int x1, y1;然后使用 super 访问 x 和 y

标签: java inheritance getter-setter


【解决方案1】:

您在子类中再次声明了 x 和 y,因此它们掩盖了超类中具有相同名称的变量

line.setX(40)

这将调用超类中的方法,从而在MyPoint中设置x

在子类中

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

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

解决方案:将 x 和 y 作为实例成员从 MySubLine 中移除

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 2019-05-04
    • 2014-06-17
    • 1970-01-01
    • 2013-11-11
    • 2023-03-19
    • 2012-06-09
    • 1970-01-01
    相关资源
    最近更新 更多