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(); } }
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.
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.
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.
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.
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(); } }
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