In my java program,I need to store the recent values in a variable and my code is as shown below
public class Exmp2
{
int noOfInstances;
public Exmp2()
{
noOfInstances++;
}
public static void main(String[] args){
Exmp2 e1=new Exmp2();
System.out.println("No. of instances for sv1 : " + e1.noOfInstances);
Exmp2 e2=new Exmp2();
System.out.println("No. of instances for sv1 : " + e2.noOfInstances);
System.out.println("No. of instances for st2 : " + e2.noOfInstances);
Exmp2 e3=new Exmp2();
System.out.println("No. of instances for sv1 : " + e3.noOfInstances);
System.out.println("No. of instances for sv2 : " + e3.noOfInstances);
System.out.println("No. of instances for sv3 : " + e3.noOfInstances);
}
}
My output should be 1 2 2 3 3 3 but am getting 1 1 1 1 1 1 can you give solution?
Declare your noOfInstances
variable as static
.
static int noOfInstances;
Since its not static
, for every new Exmp2()
a noOfInstances
is created for that instance, with the default value as 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With