Does the main method (that Java requests you have in a class) have to be static? For example I have this code
public class Sheet {
public static void main(String[] args) {
myMethod();
}
public void myMethod() {
System.out.println("hi there");
}
}
This is giving me the error
cannot make a static reference to the non-static call method from main
If I'm getting it clear, any method I call from the main method must be static, and every method I call from a static method must be static.
Why does my whole class (and if we go further, my whole program) and methods have to be static? And how can I avoid this?
Not all your methods must be static, only the main entry point for your application. All the other methods can remain non-static but you will need to use a reference of the class to use them.
Here's how your code would look like:
public class Sheet {
public static void main(String[] args) {
Sheet sheet = new Sheet();
sheet.myMethod();
}
public void myMethod(){
System.out.println("hi there");
}
}
The explanation for your concerns are explained here (there's no need to dup all the info here):
Your main method must be static because that is the single point of entry in your program for that running configuration.
A static method is bound to the class, hence it cannot know about single instances of that class.
You can invoke myMethod by instantiating your Sheet class:
new Sheet().myMethod();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With