2015-03-31 57 views
0

我使用Shape类创建了一个叫做一个对象,并且我调用实例变量x1作为'one',并通过执行int x = 1将其设置为int x。 X1;它工作正常。但是当我尝试在不同的课堂上这样做时,它根本不起作用。当我试图在不同的课程中这样做时,错误消息显示出“不能解析变量”。如果有人知道什么是错的,以及如何解决这个问题,请告诉我。谢谢。使用不同类中的对象的实例变量

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; 

} 

} 
+1

你粘贴时运作的代码。您应该粘贴不起作用的代码,以便我们可以看到您要做的事情。 – 2015-03-31 21:48:49

+2

Java中的变量不是全局变量,它们的可见性范围取决于它们定义的位置。在你的代码中,'one'是在'main()'方法内部定义的,在其外部的任何位置都不可访问也不可见。 – 2015-03-31 21:49:10

+0

变量'one'声明在哪里? – 2015-03-31 21:53:15

回答

1

这一个工程:

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; 

} 

} 

不同的类:

package events; 

public class test { 

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

} 

} 
1

你,如果你想从外部访问他们设置的变量为公共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;然后将其设置在主one = new Shape(...)并添加一个getter它public Shape getOne(){...}

然后在测试类,你可以调用getOne()和访问的变量。

+0

错误信息是“”不能解析为变量。“,所以问题出在'one',而不是'x1'。 – 2015-03-31 21:50:30

+0

我相信OP的问题是在'main()'方法 – 2015-03-31 21:50:40

+0

以外的地方使用'one',完全错过了这个。 – Epicblood 2015-03-31 21:52:13

相关问题