This time we will go back to basics and explore various aspects of the static keyword, including static classes.
Static Variables
When a variable is declared as static, it is shared among all instances of the class. In other words, all objects of that class will have the same value for the static variable. Static variables are also known as class variables since they are associated with the class itself rather than any specific instance. To access a static variable, you don't need to create an object of the class; you can directly refer to it using the class name.
class MyClass {
static int count = 0;
public MyClass() {
count++;
}
}
public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println(MyClass.count); // Output: 2
}
}
Static Methods
Similar to static variables, static methods are associated with the class itself rather than any instance of the class. They can be called using the class name without creating an object. One common use case for static methods is when you need utility methods that perform a specific task but don't require any instance-specific data.
class MathUtils {
public static int square(int num) {
return num * num;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtils.square(5);
System.out.println(result); // Output: 25
}
}
Static Classes
In Java, you can define a class as static if it is nested within another class. A static nested class is a class that belongs to the outer class itself, rather than an instance of the outer class. It can access static members of the outer class directly but requires an instance of the outer class to access non-static members. Static nested classes are often used to logically group classes only used within the outer class or when you want to hide the nested class from the outside world.
class OuterClass {
private static int outerVariable = 10;
static class InnerClass {
public void display() {
System.out.println("Outer Variable: " + outerVariable);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.InnerClass innerObj = new OuterClass.InnerClass();
innerObj.display(); // Output: Outer Variable: 10
}
}
Conclusion
The static keyword in Java provides a way to define members that are associated with the class itself, rather than any specific instance. Understanding how and when to use static variables, methods, and classes can significantly enhance your ability to write efficient and well-structured Java code.