javastaticnon-staticmembers

Difference in the number of count when count is static and non static in Java


I am trying this below program

class Car1
{
    static int count;
    Car1()
    {
        System.out.println("Car instance has been created...");
    }

    Car1(int arg) {
        System.out.println("Car instance has been created...");
    }

    Car1(double arg) {
        System.out.println("Car instance has been created...");
    }
    Car1(int arg1, double arg2) {
        System.out.println("Car instance has been crreated...");
    }
    {
        count++;
    }
}
public class MainClass10
{
    public static void main(String[] args) {
        System.out.println("Program Started");
        new Car1(11);
        new Car1(11, 12.11);
        for (int i = 0; i<9; i++)
        {
            new Car1();
        }
        Car1 c1 = new Car1(11.12);
        System.out.println("Total number of cars: " + c1.count);
        System.out.println("Program Ended");
    }
}

The output for number of count is 12 and when I try this by changing count variable as non static then 'number of count is 1'.

Could anyone please help me understand this?


Solution

  • Static means the counter will be shared across all instance of the Car1 class. On the other hand if you don't use a static counter, each instance of the Car class (each time you do a new Car1(...)) will have its own counter. It's not shared. Hence you'll only be printing the counter of instance c1.

    If you don't get it look at this post for another explanation.