2015-03-31 58 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

相關問題