Any variable or method declared static can be used regardless of the class instance.
Experiment
Try compiling this class:
public class HelloWorld { public static int INT_VALUE = 42; public static void main( String args[] ) { System.out.println( "Hello, " + INT_VALUE ); } }
This is done because the variable INT_VALUE declared static (for example, the main method).
Try compiling this class with the previous class:
public class HelloWorld2 { public static void main( String args[] ) { System.out.println( "Hello, " + HelloWorld.INT_VALUE ); } }
This succeeds because the variable INT_VALUE is both static and public . Without going into details, it is usually useful to avoid public variables.
Try compiling this class:
public class HelloWorld { public int int_value = 42; public static void main( String args[] ) { System.out.println( "Hello, " + int_value ); } }
This does not compile because an instance of the object from the HelloWorld class is missing. For this program to compile (and run) it would have to be changed:
public class HelloWorld { public int int_value = 42; public HelloWorld() { } public static void main( String args[] ) { HelloWorld hw = new HelloWorld(); System.out.println( "Hello, " + hw.int_value ); } }
Dave jarvis
source share