I started to write my first Java program.
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
The program runs fine just with the above code. But according to my OOP knowledge, a class
is only an abstract concept and doesn't come to life untill you create an object of its kind. And then, through that object we call the methods/functions inside the class.
But in this particular example, it seems that main
method is called even without creating an object of the class
HelloWorldApp
Is the object created somewhere else? If so, how does that portion of the code know my class
name HelloWorldApp
?
It is because it is static
method, and for that it doesn't need to create instance
JVM will load the HelloWorldApp
class and it will invoke static method on it, And since it is public JVM (being external ) can access this method
Also See
Starting point for a java application (not always ) is this method
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
When you do java className
it will go and check if the class has a main method, since its static it can be called without creating an instance.
If there is no main method or main method is there but not with the same signature it will throw you a RuntimeException
stating main method not found.
Don't forget to read A closer look at main method.
off topic:
Extending the same idea, you don't need an instance of a class to refer its static method and fields.
public class MyClass {
public static int NUMBER = 10;
public static void String sayHello(){
return "Hello";
}
public void String sayBye(){
return "Bye";
}
public static void main(String[] args){
System.out.println(NUMBER); // No need for object
System.out.println(sayHello()); // No need for object
System.out.println(new MyClass().sayBye()); // sayBye is not accessible at class level have to have an object of MyClass to access sayBye
}
}
If same is called in some other class then it may look like:
public class MyClassCaller {
public static void main(String[] args){
System.out.println(MyClass.NUMBER); // No need for object just refer the class
System.out.println(MyClass.sayHello()); // No need for object just refer the class
System.out.println(new MyClass().sayBye()); // sayBye is not accessible at class level have to have an object of MyClass to access sayBye
}
}
A nice discussion on usage/overusage of static methods
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