Why can't I just declare all methods static?
java
Solution
Static methods cannot access instance variables. :)
public class MyStaticExample{
private String instanceVariable = "Hello";
private static String STATIC_VARIABLE = "Hello too";
public static void staticMethod(){
System.out.println(this.instanceVariable); // this will result in a compilation error.
System.out.println(STATIC_VARIABLE); // this is ok
}
public void instanceMethod(){
System.out.println(this.instanceVariable); // this is ok
System.out.println(STATIC_VARIABLE); // this is ok
}
}
Problem
I was being questioned by this, why can't I declare all methods static? Can you give me a piece of explanation in here? Thanks. I believe that when you make a method static, it cannot access non-static members?