Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does every method in main class have to be static?

Tags:

I'm a total noob at java, but while practicing tonight it occurred to me that with OOP design every method in the main class is going to have to be static right? In this code there is no way for me to call a method within the class that isn't static.

It seems like maybe I'm missing the point of why you would declare a class static or not. Thanks for your help!

public class JavaApplication2 {  private static CreateCar Vroom; private static Limo Fuuu;  public static void main(String[] args) {      Vroom = new CreateCar();      Vroom.creator();      getGas();      addGas();      getGas();      Fuuu = new Limo();      Fuuu.creator();      Fuuu.wheels = 5;      Fuuu.wheelie(); }  public static int getGas(){      Vroom.returnGas();      return 0;  }  public static void addGas(){      Vroom.fillerUp();  }  } 
like image 706
Zombian Avatar asked Nov 14 '11 05:11

Zombian


People also ask

Do all methods in main have to be static?

The main() method in Java must be declared public, static and void. If any of these are missing, the Java program will compile but a runtime error will be thrown.

Do All methods need to be static in java?

A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without a static keyword preceding it.

What happens if main method is not static?

As discussed above, the main() method should be public, static, and have a return type void. If we do not define it as public and static or return something from the method, it will definitely throw an error.

Why the main method must be static?

In the case of the main method, it is invoked by the JVM directly, so it is not possible to call it by instantiating its class. And, it should be loaded into the memory along with the class and be available for execution. Therefore, the main method should be static.


1 Answers

You can call non-static methods, but you can only do so through an object. That is, you need to call the method on a given object.

Your main class can also be instantiated, so not every method in the main class needs to be static. For example:

public class MainClass {     int value;      public void printValue() {         System.out.println("" + value);     }      public static void main(String[] args){         MainClass o = new MainClass();         o.printValue();     } } 
like image 135
Petar Ivanov Avatar answered Oct 26 '22 23:10

Petar Ivanov