Why can't we just make all methods and variables static, to save ourselves from the hassle of making objects?
I have actually had this question ever since I started learning Java a long time ago, but never asked it. I know that if a method or variable is not static, you can call it using an object you create:
public class classwithmethodandvariable {
int i = 7;
public void hello() {
}
}
You can call this like so:
public class myMainClass {
classwithmethodandvariable obj = new classwithmethodandvariable();
classwithmethodandvariable.i++; // ACCESS INT I AND INCREMENT
classwithmethodandvariable.hello(); // CALLS METHOD HELLO
}
But, if we had made the method hello()
and variable i
we could have done everything with less lines of code, right?
public class classwithmethodandvariable {
static int i = 7;
public static void hello() {
}
}
You can call this like so:
public class myMainClass {
classwithmethodandvariable.i++; // ACCESS INT I AND INCREMENT
classwithmethodandvariable.hello(); // CALLS METHOD HELLO
}
Why don't we do that? I have seen another question like this, but the answer says “Because you can't access instance variables from static methods”. But then what if you make the variables also static
?