gpt4 book ai didi

java - 使用不同类中对象的实例变量

转载 作者:行者123 更新时间:2023-12-02 04:49:19 26 4
gpt4 key购买 nike

我使用 Shape 类创建了一个名为 one 的对象,并将实例变量 x1 称为“one”,并通过执行 int x = one.x1; 将其设置为 int x;而且效果很好。但是当我尝试在另一个类(class)中这样做时,它根本不起作用。当我尝试在不同的类中执行此操作时,会显示一条错误消息,指出“无法解析为变量”。如果有人知道出了什么问题以及如何解决此问题,请告诉我。谢谢。

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(){...}

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

关于java - 使用不同类中对象的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29379130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com