有没有人可以告诉我,在创建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)
because of this line
a1.clear();
your clear method is changing the orginal values of your static x, and y variables. Because if variable is static every object is referencing a single copy of original variable.