例如,我有 Platform 类:
public class Platform
{
double x, y;
Color c;
public Platform(double x, double y, Color c)
{
this.x = x;
this.y = y;
this.c = c;
}
}
我试图在整个其他类中创建 Platform 类的新实例后访问它的参数。变量“x”将根据上下文发生变化:
public void makePlatform() {
int x = 100;
int y = 800;
Color c;
c = new Color(1,1,1); //platform is black
Platform p = new Platform(x,y, c);
}
现在我尝试在同一个类的另一个方法中访问变量“x”:
public void run() {
while(true) {
if(right)
p.x++;
if(left)
p.x--;
if (p.x > 335 || p.x < 0) {
p.x = -p.x;
}
}
}
我知道初始化是在另一个范围内,我不知道如何使用我在另一个方法中创建的内容。
谢谢
最佳答案
平台 p = new Platform(x,y, c);
。这里的p
是makePlatform()
内部的一个局部变量,你不能在方法之外访问它。
要在方法外部访问 p
,请在 makePlatform()
外部声明它
Platform p
public void makePlatform() {
int x = 100;
int y = 800;
Color c;
c = new Color(1,1,1); //platform is black
p = new Platform(x,y, c);
rightOrLeft( p );
}
现在您可以在方法外部访问p
关于java - 如何获取我在另一个对象中创建的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62208078/