Line 1: public class C {
Line 2: public static void main(String[] args) {
Line 3: // method2();
Line 4: }
Line 5:
Line 6:
Line 7: Circle c = new Circle();
Line 8: public static void method2() {
Line 9: // Circle c = new Circle();
Line 10:
Line 11: System.out.println("What is radius "+ c.getRadius()); //compile error : non-static variable c cannot be referenced from a static context. Why? here "c" is a instance variable.
Line 12: }
Line 13:
Line 14:
Line 15: }
Line 16:
Line 17: class Circle
Line 18: {
Line 19: public int getRadius()
Line 20: {
Line 21: return 3;
Line 22: }
Line 23: }
Question : in line 11 ,compile error says, non-static variable c cannot be referenced from a static context. Why? here "c" is a instance variable. But the following code is ok . Why?
if I change From line 8 to 12
public static void method2() {
Circle c = new Circle();
System.out.println("What is radius "+ c.getRadius());
}
Or:
Circle c = new Circle();
public void method2() {
System.out.println("What is radius "+ c.getRadius());
}
Circle c = new Circle();is not declared as static but as instance variable ofC, you need to make the declaration static i.e.static Circle c = new Circle();or an enclosing instance ofCwhich in turn has to be declared asstatic.