counter without static variable, problem

Java Programming Language / Class, Object and Methods in java

28021

Program:

 class CounterClass{
int count=0;//will get memory when instance is created

CounterClass(){
count++;
System.out.println(count);
}

public static void main(String args[]){

CounterClass c1=new CounterClass();
CounterClass c2=new CounterClass();
CounterClass c3=new CounterClass();

 }
}

/*
 problem with instance variable:

 instance variable gets the memory at the time of object creation,
 each object will have the copy of the instance variable, if it is
 incremented, it won't reflect to other objects. So each objects will
 have the value 1 in the count variable.
 */

Output:

1
1
1
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.