2016-11-29 34 views
-3

這裏我使用static關鍵字來實例化一個變量而我使用兩個不同的對象調用變量。我想打印結果爲1和2而不使用static關鍵字。提前感謝。增加一個變量而不使用靜態關鍵字

public class Test { 
    static int a = 1; 

    public void meth() { 
     System.out.println(a); 
     a = a + 1; 
    } 

    public static void main(String[] args) { 
     Test a = new Test(); 
     Test b = new Test(); 
     a.meth(); //prints 1 
     b.meth(); //prints 2 
    } 

} 
+1

分配的問題? –

+0

當您刪除static關鍵字時,a的值不再在「Test」的兩個實例中共享。因此,由於每個實例都有自己的計數變量,因此您的輸出將爲「1 1」。 – f1sh

+1

'a'在所有實例之間共享。如果你刪除了'static',它將與每個實例關聯。創建一個實例並調用兩次「meth」 - 第一個調用將打印1,第二個將打印2。 – Maroun

回答

0

如果刪除static關鍵字,你需要在你的Test兩個實例共享一個int變量。

例如,使用AtomicInteger作爲int一個可變包裝和提供所述對象構建Test時:

public class Test { 
    private final AtomicInteger a; 
    // + constructor setting a + getter 

    public void increment() { 
     a.incrementAndGet(); 
    } 

} 

public class Main { 
    public static void main(String[] args) { 
     AtomicInteger i = new AtomicInteger() 
     Test a = new Test(i); 
     Test b = new Test(i); 

     System.out.println(i.get()); // prints 0 
     a.increment(); 
     System.out.println(i.get()); // prints 1 
     b.increment(); 
     System.out.println(i.get()); // prints 2 

    } 
} 
相關問題