递增1并将其与每个创建的对象相加? [英] increments by 1 and add it with every created object?
问题描述
class MyObject {
static int instanceCounter = 0;
static int counter = 0;
MyObject() {
instanceCounter++;
counter = counter + 1;
}
}
我正在使用静态整数获取此输出:
I am using the static ints to get this output:
对象1:5的instanceCounter的值
Value of instanceCounter for Object 1: 5
MyObject的instanceCounter的值:5
Value of instanceCounter for MyObject: 5
对象1的计数器值
对象2的计数器值2
对象3的计数器值
对象4的计数器值:4
Value of Counter for Object 4: 4
对象5的计数器值:5
Value of Counter for Object 5: 5
但显示
对象1:5的instanceCounter的值
Value of instanceCounter for Object 1: 5
MyObject的instanceCounter的值:5
Value of instanceCounter for MyObject: 5
对象1的计数器值5
对象2的计数器值5
对象3的计数器值5
对象4的计数器值:5
Value of Counter for Object 4: 5
对象5的计数器值: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);
}
}
如果我删除了static,这就是它显示的内容
and if i remove static this is what it displays
对象1:5的instanceCounter的值
Value of instanceCounter for Object 1: 5
MyObject的instanceCounter的值:5
Value of instanceCounter for MyObject: 5
对象1的计数器值
对象2的计数器值
对象3的计数器值
对象4的计数器值:1
Value of Counter for Object 4: 1
对象5的计数器值:1
Value of Counter for Object 5: 1
推荐答案
由于instanceCounter是静态变量,因此所有对象共享同一变量.由于在每个对象构造期间都增加instanceCounter,因此在创建5个对象结束时,其值为5. 因此,您在所有系统输出中的输出均为5.多数民众赞成在静态点
Since instanceCounter is a static variable, all objects share the same variable. Since you are incrementing the instanceCounter during each object construction, at the end of creating 5 objects, its value is 5. Consequently you get the output as 5 in all your sys outs. Thats the point of static
编辑
要实现您所需要的,请执行以下操作:
EDIT
To achieve what you need, do the following:
class MyObject {
static int instanceCounter = 0;
int counter = 0;
MyObject()
{
instanceCounter++;
counter = instanceCounter;
}
}
这篇关于递增1并将其与每个创建的对象相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!