class MyObject {
static int instanceCounter = 0;
static int counter = 0;
MyObject() {
instanceCounter++;
counter = counter + 1;
}
}
この出力を取得するために静的 int を使用しています。
オブジェクト 1 の instanceCounter の値: 5
MyObject の instanceCounter の値: 5
オブジェクト 1 のカウンターの値: 1
オブジェクト 2 のカウンターの値: 2
オブジェクト 3 のカウンターの値: 3
オブジェクト 4 のカウンターの値: 4
オブジェクト 5 のカウンターの値: 5
しかし、その表示
オブジェクト 1 の instanceCounter の値: 5
MyObject の instanceCounter の値: 5
オブジェクト 1 のカウンターの値: 5
オブジェクト 2 のカウンターの値: 5
オブジェクト 3 のカウンターの値: 5
オブジェクト 4 のカウンターの値: 5
オブジェクト 5 のカウンターの値: 5
私のランナークラス
class RunMyObject {
public static void main(String[] args) {
MyObject Object1 = new MyObject();
MyObject Object2 = new MyObject();
MyObject Object3 = new MyObject();
MyObject Object4 = new MyObject();
MyObject Object5 = new MyObject();
System.out.println(“Value of instanceCounter for Object 1: ” + Object1.instanceCounter);
System.out.println(“Value of instanceCounter for MyObject: ” + MyObject.instanceCounter);
System.out.println(“Value of Counter for Object 1: ” + Object1.counter);
System.out.println(“Value of Counter for Object 2: ” + Object2.counter);
System.out.println(“Value of Counter for Object 3: ” + Object3.counter);
System.out.println(“Value of Counter for Object 4: ” + Object4.counter);
System.out.println(“Value of Counter for Object 5: ” + Object5.counter);
}
}
そして、静的を削除すると、これが表示されます
オブジェクト 1 の instanceCounter の値: 5
MyObject の instanceCounter の値: 5
オブジェクト 1 のカウンターの値: 1
オブジェクト 2 のカウンターの値: 1
オブジェクト 3 のカウンターの値: 1
オブジェクト 4 のカウンターの値: 1
オブジェクト 5 のカウンターの値: 1