Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the main method belong to any class?

Tags:

java

Does the main method belong to any class?

like image 564
billu Avatar asked May 27 '10 11:05

billu


People also ask

Can I call Main method from another class?

To do that, first, we need to create an object of “FirstClass” in the main method of the “SecondClass”. Once an object of the “FirstClass” is created, then we can invoke any method or attribute of the “FirstClass” within the “SecondClass” using that object.

Can the main method be in a subclass?

Well, it depends, But usually main method put in sub class. There is quite big difference between in inheritance and shadowing. But you can put it subclass or super class. Remember main method is static.

Can we run main method without class in java?

Yes, you can compile and execute without main method by using a static block. However, after static block executes, you will get an error saying no main method found.

Can two classes have main method?

Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.


3 Answers

It does belong to a class. Look at any hello-world implementation and it would be clear to you.

public static void main(String[] args) {
    System.out.println("Hello World");
}

won't compile as it stands. You need to put class HelloWorld { ... } around it, in which case you may say that the main method "belongs" to the HelloWorld class.

However, since it's static, it does not belong to any particular object. There is an important difference between classes and objects that you need to get acquainted with when working with object oriented languages. Learning Java: Objects and Classes is a good starting point.

like image 131
aioobe Avatar answered Nov 14 '22 14:11

aioobe


Yes. Every method or field must belong to a class (or interface/enum).

like image 32
Joachim Sauer Avatar answered Nov 14 '22 13:11

Joachim Sauer


Every line of Java code (except import/package) lives in a class (or is a class/interface declaration). So does main.

like image 24
miku Avatar answered Nov 14 '22 13:11

miku