你能告诉我在创建 a2 对象后为什么构造函数没有改变值吗
Could you please tell me that after creating the a2 object why didnt the constructor changed the values
谁能告诉我在创建 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?
}
}
因为这条线
a1.clear();
您的清除方法正在更改静态 x 和 y 变量的原始值。因为如果变量是静态的,每个对象都引用原始变量的单个副本。
谁能告诉我在创建 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?
}
}
因为这条线
a1.clear();
您的清除方法正在更改静态 x 和 y 变量的原始值。因为如果变量是静态的,每个对象都引用原始变量的单个副本。