2014-07-06 63 views
-1

我有一個類包含一個靜態變量,但沒有返回我所期望的。靜態變量不會返回Java中預期的內容

public class helper { 
    public static int a = 5; 
} 

該類達到靜態變量並對其進行更改。

public class alistirma { 
    public static void main(String args[]){ 
     System.out.println(helper.a); 
     helper.a += 3; 
     System.out.println(helper.a); 
    } 
} 

不過我預計代碼返回8,但它返回5.

public class dummy { 
    public static void main(String[] args) { 
     System.out.println(helper.a); 
    } 
} 
+3

是否運行了'main'? –

+3

該值不會持續執行同一程序。我認爲這是你的誤解。 – Brian

+1

如果各種程序引用相同的靜態變量,這並不意味着它們奇蹟般地共享一個變量,每個程序都會分配它自己的靜態變量。 –

回答

0

你有兩個public static void Main(String args []){}函數,所以刪除其中的一個。也許改變你alistirma類這樣的:

public class alistirma { 
public static void changeValue{ 
    System.out.println(helper.a); 
    helper.a += 3; 
    System.out.println(helper.a); 
} 

}

然後,讓你的虛擬級呼叫alistrima的changeValue方法。

public class dummy { 
public static void main(String[] args) { 
    alistirma.changeValue(); 
    //System.out.println(helper.a); don't need this now 
} 

}

4

每次運行程序一切從頭開始下載的時間。除非你在主要方法alistirma之前主要方法虛擬你只會得到初始值爲helper.a