我使用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;
}
}
你粘貼時運作的代碼。您應該粘貼不起作用的代碼,以便我們可以看到您要做的事情。 – 2015-03-31 21:48:49
Java中的變量不是全局變量,它們的可見性範圍取決於它們定義的位置。在你的代碼中,'one'是在'main()'方法內部定義的,在其外部的任何位置都不可訪問也不可見。 – 2015-03-31 21:49:10
變量'one'聲明在哪裏? – 2015-03-31 21:53:15