increments by 1 and add it with every created object?
java, oop
Solution
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;
}
}
Problem
``` 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: 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 but its displaying 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 my runner class ``` 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); } } ``` and if i remove static this is what it displays 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