2017-10-14 49 views
-1

任何人都可以告訴我,創建a2對象後爲什麼沒有構造函數更改值?你能告訴我,創建a2對象後爲什麼沒有構造函數更改值

public class HelloWorld 
{ 
    static int x;  // static datamembers 
    static int y;  // static datamembers 

    HelloWorld()  //constructor 
    { 
     x = 9999; 
     y = 9999; 
    } 

    static void display()  // static method 
    { 
     System.out.println("The value of x is:"+x); 
     System.out.println("The value of y is:"+y); 
    } 

    void clear() 
    { 
     this.x = 0;  // this pointer 
     this.y = 0;  // this pointer 
    } 

    public static void main(String []args) 
    { 
     HelloWorld a1 = new HelloWorld();  // instance of class 
     HelloWorld a2 = new HelloWorld();  // instance of class 

     a1.display();  // a1 object calls the display 
     a1.clear();   // this pointer clears the data 
     a1.display();  // cleared data is displayed 

     a2.display();  // a2 object calls the display but the values are 0 and 0 why not 9999 and 9999, why didn't the constructor get called? 
    } 
} 
+0

你運行你的程序,它的值更改爲0和0,你的問題與它的身體無關嗎?你需要了解關於靜態在Java中https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html – 2017-10-14 14:43:42

+0

這是什麼編程語言?請用正在使用的語言標記您的問題。要更新您的問題,請點擊帖子下的**「[edit]」**鏈接。謝謝。 – Pang

回答

0

,因爲這條線 a1.clear(); 您的清零方法是改變你的靜態x的原單值,和y變量。因爲如果變量是靜態的,則每個對象都引用原始變量的單個副本。

相關問題