在不同的 class 中使用对象的实例变量

Using an instance variable of an object in a different class

我使用 Shape class 创建了一个名为 one 的对象,并为 'one' 调用了实例变量 x1,并通过执行 int x = one.x1; 将其设置为 int x;它工作正常。但是当我尝试在另一个 class 中这样做时,它根本不起作用。当我尝试在另一个 class 中执行此操作时,出现了一条错误消息,上面写着 "one cannot be resolve to a variable." 如果有人知道出了什么问题,以及如何解决这个问题,请告诉我。谢谢你。

package events;

public class Shape {

int x1;
int x2;
int y1;
int y2;
int width;
int height;

Shape(int x1, int y1, int width, int height) {

    this.x1 = x1;
    this.y1 = y1;
    this.width = width;
    this.height = height;
    this.x2 = x1 + width;
    this.y2 = y1 + height;

}

public static void main(String[] args){

    Shape one = new Shape(4,4,4,4);

    int x = one.x1;

}

}

无效的代码:

package events;

public class test {

public static void main(String[] args){
    int x = one.x1;

}

}

如果要从外部访问它们,您必须将变量设置为 public public int x1;

不过,最好使用 getter 和 setter:

//things
private int x1;
//more stuff
public int getx1(){
    return x1;
}
public void setX1(int x){
    x1 = x;
}

编辑:

看来我错过了问题的重点,要真正回答它,您不能访问变量定义位置之外的变量。如果你想在其他地方使用 one,你必须为它创建一个 setter,或者在更广泛的范围内定义它。

如果必须的话,我建议像上面那样做,定义 private Shape one; 然后在 main one = new Shape(...) 中设置它并为它添加一个 getter public Shape getOne(){...}

然后在测试中 class 您可以调用 getOne() 并访问变量。

这个有效:

package events;

public class Shape {

int x1;
int x2;
int y1;
int y2;
int width;
int height;
static Shape one = new Shape(4,4,4,4);

Shape(int x1, int y1, int width, int height) {

    this.x1 = x1;
    this.y1 = y1;
    this.width = width;
    this.height = height;
    this.x2 = x1 + width;
    this.y2 = y1 + height;

}

public static void main(String[] args){


    int x = one.x1;

}

}

一个不同的 class:

package events;

public class test {

public static void main(String[] args){
    int x = Shape.one.x1;

}

}