2017-10-14 48 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变量。因为如果变量是静态的,则每个对象都引用原始变量的单个副本。

相关问题