A static method (context) cannot directly access instance members (variable and method) of a class. It can only access the static members directly.
public class Test {
private int i;
private static int j;
public void m1() {
System.out.println("Inside method m1");
}
public static void m2() {
System.out.println("Inside method m2");
}
public static void m3() {
j = 3;
m2(); // can access static members
Test t = new Test();
t.i = 4; // can access instance members
t.m1(); // indirectly (on a reference)
i = 3; // cannot access instance members
m1(); // directly - will not compile
}
}
No comments:
Post a Comment