Understanding Static in Java
The keyword static tells Java that a particular property, method, or code block belongs to the class itself, rather than any individual instance of that class. Lets look at the difference between static and non-static properties.
class MyClass {
public int notStaticInt;
public static int staticInt;
} //MyClass
public class MainClass {
public static void main(String[] args) {
MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();
myClass1.notStaticInt = 1;
myClass2.notStaticInt = 2;
myClass1.staticInt = 3;
myClass2.staticInt = 4;
System.out.println("myClass1: " + myClass1.notStaticInt);
System.out.println("myClass2: " + myClass2.notStaticInt);
System.out.println("myClass1: " + myClass1.staticInt);
System.out.println("myClass2: " + myClass2.staticInt);
} //main
} //MainClass
myClass1: 1 myClass2: 2 myClass1: 4 myClass2: 4
If you make a method of a class static, then you can call the method without even having to create an instance of the class.
class MyClass { static void speak() { System.out.println("Hello my friends!"); } } //MyClass public class MainClass { public static void main(String[] args) { MyClass.speak(); } //main } //MainClass
class MyClass { static int myInt; static { myInt = 3; } } //MyClass public class MainClass { public static void main(String[] args) { MyClass myClass1 = new MyClass(); System.out.println(myClass1.myInt); } //main } //MainClass
It is especially useful for complex initialization logic like error handling.
Here is an example...
class MyClass { static { try { someStaticResource = loadResource(); } catch (IOException e) { System.err.println("Error loading resource"); } } } //MyClass
And here is something interesting... A class can have both a default constructor and a static block, and they serve different purposes: the static block is for class-level initialization, while the constructor is for instance-level initialization. They do not conflict with each other and can work together.
Comments
Post a Comment