Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does actually 2 classes work in one program?

Tags:

java

I probably have quite a big misconception, and I've been looking around the internet and still cant find the answer to my question. So in java OOP, suppose I have 2 classes one called Main.java, the other Something.java, and because each classes both have their own entry point in their main method.

  1. which one should I start the program with (like to call all the other classes in that program)?
  2. And, if I were to use Main.java class, how do I call the whole things happening in Something.java? Like if that class was made to do its whole thing, with its own method, variables and all, and I'm just calling it all in the Main.java?

It's quite easy to understand theoretically, but in a program, not so much for me for some reason.

like image 557
VerzChan Avatar asked May 31 '26 15:05

VerzChan


1 Answers

Well it's you who have to decide your entrypoint class. If you decide Main to be entry point class your other main method will treated as normal method like other methods. Hence, you can call that in entrypoint class.

Example below:

public class MultipleMain {

    public static void main(String[] args) {
        System.out.println("Hello World!!!! I must be executing");
        AnotherWithMain.main(new String[]{});
    }
}


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

If you call MultipleMain class i.e. java MultipleMain then output would be:

Hello World!!!! I must be executing
Hello World

and if you call AnotherWithMain then Hello World will be printed per above impl.

like image 151
Vinay Prajapati Avatar answered Jun 02 '26 21:06

Vinay Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!