Search code examples
javainheritancemain-method

Inheriting the main method


I want to define a base class that defines a main method that instantiates the class, and runs a method. There are a couple of problems though. Here is the base class:

public abstract class Strategy
{
    abstract void execute(SoccerRobot robot);

    public static void main(String args)
    {
        Strategy s = new /*Not sure what to put here*/();
        s.execute(new SoccerRobot())
    }
}

And here is an example derived class:

public class UselessStrategy
{
    void execute(SoccerRobot robot)
    {
        System.out.println("I'm useless")
    }
}

It defines a simple execute method, which should be called in a main method upon usage as a the main application. However, in order to do so, I need to instantiate the derived class from within the base class's main method. Which doesn't seem to be possible.

I'd rather not have to repeat the main method for every derived class, as it feels somewhat unnessary.

Is there a right way of doing this?


Solution

  • Move the main method out into a separate class. Separate concerns
    Strategy (the name says it all)
    Launcher (assembling components together and triggering execution)

    public class Launcher
    {
        public static void main(String args)
        {
           Strategy s = new UselessStrategy();
              //OR Strategy s = CreateInstance(args[0]) ;
              //OR equiv mechanism for Dependency Injection if you don't want to hardcode the derived strategy to use.
            s.execute(new SoccerRobot())
        }
    }