Java理解继承:来自父类的getter和setter

问题描述 投票:0回答:1

再次是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方法?

任何帮助将不胜感激!

java inheritance getter-setter
1个回答
1
投票

您在子类中再次声明了x和y,因此它们使超类中的x和y黯然失色

line.setX(40)

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

在子类中

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.