Question

I have a doubt about Java.

In a Java project (handled by Eclipse for example), can I have more classes that contain the main() method and consequently can I chose to execute one class or another class?

Tnx

Andrea

Was it helpful?

Solution 2

Yes, you can have more classes that contain the main() method, but at least one class which contain main() should be public so that JMV will start that class as Main thread

  • as the code written by aUserHimself represent

OTHER TIPS

You can have as many Classes as you want as long as each class have single main method.

You'll have to be opening a Specific Class in Eclipse if you wanna run main in that class or you can choose previously run classes from Eclipse Run Menuitem.

main means public static void main(String[] args) which is entry point in java programs.

Yes, you can have as many public static void main(String args[]) methods as classes. You can also have more of them in the same file. For example, inside Class2.java you can have:

class Class1 {
    public static void main(String args[]) {
    }
}
public class Class2 {
    public static void main(String args[]) {
    }
}

Let me sum up the points regarding main method in JAVA (which is confusing at the beginning).

1. can we have more than one main() method in a class? Ans: Yes. You can have more than one method with the name main but different signature. These methods will be overloaded. BUT the main method with following sigature will be treated as app entry point.

public static void main(String args[]) which is same as public static void main(String... args) or public static void main(String[] args)

2. can we have more than one main method in a java program? Ans: Yes. We can have different classes having the main methods.

Then which one will be treated as app entry point?

While running a program with such classes, the user will be asked to choose among the classes to act as entry point.

Yes you can have more classes that contain public static void main(String[] args). And you can chose to execute one class or another class. However, you can't have more than one main method within same class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top