我如何在构造函数中设置变量并稍后在程序中使用 "getter" 方法? (Java)

How can i setup a variable inside a constructor and use a "getter" method later on in the program on it? (Java)

我的作业卡住了,需要一些帮助

在实例变量部分,我们只允许使用以下内容:

private int _width;
private int _height;
private Point _pointSW; // point is basically (x,y)

我已经创建了一个构造函数,但我现在对如何在构造函数中创建一个 _pointNW 变量感到困惑,我以后可以在“getter”方法中使用它,这是我的构造函数,请注意我不确定如何正确创建 _pointNW,因为这是我第一次没有私有变量来连接它们,所以我不知道如何正确地做到这一点,我也担心别名,所以我不确定我是否必须在这里使用新的:

public RectangleA(Point sw, Point ne) {
    _pointSW = new Point(sw);
    Point _pointNW = new Point(ne);
}

我不允许将 _pointNW 添加到私有部分,所以这也让我感到困惑,我究竟应该如何在构造函数中设置它,以便我最终可以在 getter 中使用它?

最后我应该检索到 _pointNW 以用于以下“getter”:

public Point getPointNE(){ }

有人可以帮忙吗?已经尝试了一个小时,但不知道该怎么做...

一种方法是创建一个新的实例变量。但由于作业的缘故,您似乎不想这样做。

另一种方法是在getter中计算。您有 SW 点、宽度和高度。所以你可以加上或减去宽度和高度来计算出 NE 点。是加还是减取决于原点在哪里,你没有指定。

所以你有N/E(top/right)和S/W(bottom/left),N/W(top/left)是组合这两个,例如

public Point getPointNW() {
    return new Point(_sw.x, _ne.y);
}

我认为赋值的思路是在不存储的情况下为NE点创建一个getter。这意味着您必须将计算该点所需的信息存储在 getter 中。您可以使用高度和宽度来执行此操作:

import java.awt.Point;
public class RectangleA {
    private int _width;
    private int _height;
    private Point _pointSW;   

    public RectangleA(Point sw, Point ne) {
        // This assumes (0,0) is in the nw corner
        this._pointSW = new Point(sw); // Save the coordinates of the sw point
        this._width = ne.x - sw.x; // Save the width based on the difference between the two points' x values
        this._height = sw.y - ne.y; // Save the height based on the difference in y values
    }
    public Point getPointNE() {
        // We don't store the ne point so we calculate it based on the sw point and the height and width
        int neX = this._pointSW.x + this._width; // The sw x + width is the ne X coordinate
        int neY = this._pointSW.y - this._height; // The sw y - height is the ne Y coordinate
        Point result = new Point( neX, neY ); // construct that point and return it
        return result;
    }
}