Static elements belong to the class. Therefore, the best way to access them is via the class. So in your case, the print out should be.
System.out.println(CarCounter.getCounter());
This may feel triviaval unnecessary but it is not. Consider the following code
// VehicleCounter.java public class VehicleCounter { static int counter = 0; public VehicleCounter(){ counter++; } public static int getCounter(){ return counter; } } // CarCounter.java public class CarCounter extends VehicleCounter { static int counter = 0; public CarCounter(){ counter++; } public static int getCounter(){ return counter; } } // CarCounterTest.java public class CarCounterTest { public static void main( String args[] ){ VehicleCounter vehicle1 = new VehicleCounter(); VehicleCounter vehicle2 = new CarCounter(); System.out.println(vehicle1.getCounter()); System.out.println(vehicle2.getCounter()); } }
What should the above code prints?
The behaviour of the above code is hard to define. vehicle1 is declared as VehicleCounter and the object is actually a VehicleCounter so it should print 2 (two vehicles are created).
vehicle2 is declared as VehicleCounter but the object is actuall CarCounter. Which should be printed?
I really don't know what will be printed but I can see that it can easily be confused. So for a better practice the static elements should always be accessed via the class it defined.
It much easier to predict what to be printed by the following code.
// CarCounterTest.java public class CarCounterTest { public static void main( String args[] ){ VehicleCounter vehicle1 = new VehicleCounter(); VehicleCounter vehicle2 = new CarCounter(); System.out.println(VehicleCounter.getCounter()); System.out.println(CarCounter .getCounter()); } }
Hope this explains.
NawaMan :-D