Question
What does the 'static' keyword do in a Java class?
package hello;
public class Hello {
static Clock clock = new Clock();
public static void main(String args[]) {
clock.sayTime();
}
}
Answer
In Java, the 'static' keyword is a modifier that alters the behavior of a class's members (variables and methods). When a member is declared as static, it is associated with the class itself rather than any specific instance of that class.
package hello;
public class Hello {
static Clock clock = new Clock(); // static global variable
public static void main(String args[]) {
clock.sayTime(); // Accessing static variable directly
}
}
Causes
- The error message 'Cannot access non-static field in static method main' occurs because the main method is static and cannot directly access instance members without an object reference.
- By declaring 'clock' as static, it becomes class-level and can be accessed directly by static methods like 'main'.
- Static members exist independently of any instances of the class, allowing them to be used without creating an object.
Solutions
- Declare members that need to be accessed in static methods as static to ensure they can be accessed directly.
- Use instance members (non-static) only when you have an instance of the class.
- If there's a need to access instance data from a static context, create an object of the class and access the instance members through that object.
Common Mistakes
Mistake: Declaring instance variables as static.
Solution: Only declare static for fields and methods that are shared across instances or do not rely on instance-specific data.
Mistake: Forget to create an instance to access non-static fields in static methods.
Solution: Always ensure to create an instance of the class before trying to access instance fields in static methods.
Helpers
- static keyword in Java
- Java class static members
- Java static methods
- Java programming concepts
- understanding static keyword