Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I put main method in superclass or subclass in Java

Tags:

java

If a class has inheritance in a Java program, do I need to put main method in the superclass or subclass? Many programs put the main method in different positions. Can anybody tell me how to do that? Thanks a lot!

like image 311
typeof programmer Avatar asked Mar 06 '26 09:03

typeof programmer


2 Answers

I think it might be best to have a simple class whose sole dedicated purpose is to contain the static main method. It simple and clear.

Your main method would then get things started by creating the initial objects from your program.

like image 80
hvgotcodes Avatar answered Mar 07 '26 23:03

hvgotcodes


You could create a new dedicated class, let's say Launcher, with a main method, instantiate your classes there, and manage any unexpected exceptions:

public class Luncher{

  public static void main(String args){
    //insert argument checking logic

    try{
      new MyClass.executeLogic(someArguments);
    }catch(Exception e){
      //insert exception handling logic here
    }

}
like image 29
Morfic Avatar answered Mar 07 '26 22:03

Morfic



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!