You must be confused about the usage of static variables
.
static class variables
are created once per class. They are shared by all class instances where as non-static class variables
are created for every object instance.
So if your counter
variable is static
it will be created only once and shared by all instances your class.
When you access it with MyObject.counter
or object1.counter
and so on, you are accessing the same counter
variable as static
variables can be accessed with a class name as well as with an instance variable.
And if it is non-static
and every instance(or object) of your class will have its own copy of counter
.
So each of your Object1
, Object2
and so on will all have their own counter
variable.
And all of them will have value 1 and so you get 1 in the output.
UPDATE:
Change your code to get your desired output that you have mentioned in a comment of one of the answers:
MyObject Object1 = new MyObject();
System.out.println(“Value of Counter for Object 1: ” + Object1.counter);
MyObject Object2 = new MyObject();
System.out.println(“Value of Counter for Object 2: ” + Object2.counter);
MyObject Object3 = new MyObject();
System.out.println(“Value of Counter for Object 3: ” + Object3.counter);
MyObject Object4 = new MyObject();
System.out.println(“Value of Counter for Object 4: ” + Object4.counter);
MyObject Object5 = new MyObject();
System.out.println(“Value of Counter for Object 5: ” + Object5.counter);
System.out.println(“Value of instanceCounter for Object 1: ” + Object1.instanceCounter);
System.out.println(“Value of instanceCounter for MyObject: ” + MyObject.instanceCounter);