gpt4 book ai didi

java - 递增 1 并将其添加到每个创建的对象中?

转载 作者:搜寻专家 更新时间:2023-10-31 08:12:25 27 4
gpt4 key购买 nike

<分区>

class MyObject {

static int instanceCounter = 0;

static int counter = 0;

MyObject() {

instanceCounter++;

counter = counter + 1;

}

}

我正在使用静态整数来获取此输出:

Value of instanceCounter for Object 1: 5

Value of instanceCounter for MyObject: 5

Value of Counter for Object 1: 1

Value of Counter for Object 2: 2

Value of Counter for Object 3: 3

Value of Counter for Object 4: 4

Value of Counter for Object 5: 5

但它显示

Value of instanceCounter for Object 1: 5

Value of instanceCounter for MyObject: 5

Value of Counter for Object 1: 5

Value of Counter for Object 2: 5

Value of Counter for Object 3: 5

Value of Counter for Object 4: 5

Value of Counter for Object 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);

}

}

如果我删除静态,这就是它显示的内容

Value of instanceCounter for Object 1: 5

Value of instanceCounter for MyObject: 5

Value of Counter for Object 1: 1

Value of Counter for Object 2: 1

Value of Counter for Object 3: 1

Value of Counter for Object 4: 1

Value of Counter for Object 5: 1

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com