Non-Static Field Reference from Static Method
In Java, a static reference cannot be made to a non-static field or method. This is because, unlike non-static fields and methods, static elements exist independently of an instance of the class.
Consider the following code:
public class NonStaticFieldReference { private float r; // Non-static field public static void main(String[] args) { System.out.println(r); // Error! c_area(); // Error! } private static void c_area() { // Cannot reference non-static field r from static method } }
In this example, the main() method is static, meaning it does not have access to the non-static field 'r'. Similarly, the static method c_area() cannot access the non-static field 'r'.
Solution
To resolve this issue, create an instance of the class and access the non-static fields and methods through that instance.
public class NonStaticFieldReference { private float r; // Non-static field public static void main(String[] args) { NonStaticFieldReference instance = new NonStaticFieldReference(); instance.r = 5; instance.c_area(); } private void c_area() { // Access non-static field r from non-static method } }
This way, the non-static field 'r' is accessed through an object of the class, allowing for proper field reference.
The above is the detailed content of Why Can\'t a Static Method Access a Non-Static Field in Java?. For more information, please follow other related articles on the PHP Chinese website!