Quick Answer
Resolve non-static reference in static context.
Understanding the Issue
Occurs when trying to access instance members from static methods. Static methods belong to the class, not instances.
The Problem
This code demonstrates the issue:
Java
Error
public class Util {
private String name;
public static void print() {
System.out.println(name); // Error
}
}
The Solution
Here's the corrected code:
Java
Fixed
// Solution 1: Make member static
private static String name;
// Solution 2: Use instance method
public void print() {
System.out.println(this.name);
}
// Solution 3: Pass instance as parameter
public static void print(Util util) {
System.out.println(util.name);
}
Key Takeaways
Understand static vs instance contexts in Java.