Ask coding questions

← Back to all posts
How do I make multiple classes and name them in java?
JavasLava (0)

Whenever I make 2 classes I sometime's put Main as its both of there names, but then I create an Error, So I obviously rename the second class, but it still only calls the first class, Not the second.

p.s I am also a beginner.

Commentshotnewtop
goodboi (0)

As @mwilki7 stated above JVM can only execute one main() to run, but you can call the other main() as you would call any other method in java.

To put it simply:

  • You cannot have multiple classes with same names in the same package.
  • Even if you have different names for both the classes with main() in them, JVM will only call the main() of one particular class, the class you specify while running java <class name> on the command line.

Here is a StackOverflow question regarding this topic: Can there exist two main methods in a Java program?

Hope this helps you :)

mwilki7 (186)

The java virtual machine can only pick a single main() to run its main thread. If you want to call both, and have fairly deterministic results, do:

class Main
{
    ....
    public static void main(String args[])
    {
        ....
        class Main2;
        Main2.run();
    }
}

class Main2
{
    ....
    public static void run()
    {
        ....
    }
}