How to run multiple classes in Java?

In a Java program, multiple classes can exist, but only one class can contain the main method as it serves as the entry point of the program. If you want to run multiple classes, you can create objects of other classes within the main method of the main class and then call their methods. For example:

public class MainClass {
    public static void main(String[] args) {
        OtherClass other = new OtherClass();
        other.method();
    }
}

public class OtherClass {
    public void method() {
        System.out.println("Hello from OtherClass!");
    }
}

In the example above, MainClass serves as the main class, which includes the main method. Within the main method, an object of OtherClass called ‘other’ is created and its method is invoked. Upon running the MainClass class, the output will be “Hello from OtherClass!”.

Note: If other classes are static classes, static methods can be called directly by the class name without needing to create an object.

bannerAds