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();
、clearメソッドは静的x変数とy変数の元の値を変更しています。変数が静的である場合、すべてのオブジェクトが元の変数の単一のコピーを参照しているためです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加