Example:

public class Counter { private int count; public static void main(String args[]){ System.out.println(count); //compile time error } } 

Example 2:

 public class Counter { public int count = 0; } public class MyProgram { public static void main(String args[]){ Counter c = new Counter(); System.out.println(c.count); //OK } } 
  • 3
    Do not you think that the examples are not equivalent? Why in the first case not Counter c = new Counter(); System.out.println(c.count); Counter c = new Counter(); System.out.println(c.count); which by the way will work fine? - Regent
  • I think it will be useful - docs.oracle.com/javase/tutorial/java/javaOO/classvars.html - Artem Konovalov
  • @pavlofff correctly said - when calling a static function in a class, the class itself is not created. You can access either the static values ​​of the classes, or the variables created inside the static function as in your example. - Daniel Protopopov

1 answer 1

Within one class, non-static variables do not exist without creating an instance of the class and cannot be used directly in static methods.

In the second case, you create an instance of the class and in the static method use the value of the variable of this instance.

Such a construction (equivalent to the first version) will also not be compiled:

 public class Counter { public int count = 0; } public class MyProgram { public static void main(String args[]){ System.out.println(Counter.count); //NOT OK } }