When we try to access non static variable from static method compiler will throw error
static reference to the non-static field
With Error code
JavaNonStaticExample.java
public class JavaNonStaticExample {
int a = 1;
public static void main(String[] args) {
System.out.println("static variable a:"+a);
// Error by compiler
// Cannot make a static reference to the non-static field a
}
}
To Remove error, you need to make a variable as static
Without Error code
public class JavaNonStaticExample {
static int a = 1;
public static void main(String[] args) {
System.out.println("static variable a:"+a);
// No Error by compiler
}
}



Link to Us