Extending the main class in Java

I need to extend the functionality of my main class, by overriding some of its methods. I was expecting that the class extending the main class would be able to be run. However, Eclipse doesn't recognize MyLauncher as a runnable class. In the following code, I have a setup() method that is overridden by the subclass. What I want is a way to run the main(..) from the super class but also the setup from the subclass.

// Launcher.java
public class Launcher {

    Launcher instance;

    public static void main (args[]) {
        instance = new Launcher(); // This is likely the problem
        instance.setup();
    }

    public void setup() {
        System.out.println("Default agent setup.");
    }
}

// MyLauncher.java
public class MyLauncher extends Launcher {

    public void setup() {
        System.out.println("New agent setup!");
    }
}

I accept alternatives to this. I can't add a main method to the subclass, though. The Launcher class is inside an API i'm making, so it can't refer to the class MyLauncher that is using the API.

edit: I think this is to specific to my problem. I decided to search for a new approach. Since I'm working with JDT, I'm going to parse the Launcher and inject the class.

Jon Skeet
people
quotationmark

As you say, the fact that you create an instance of Launcher directly in main means that no inheritance is available. Even if you could start MyLauncher easily from Eclipse, within the main method you wouldn't know which type had actually been used to start it. I can't see any easy solution that doesn't involve either creating a main method in each class or providing the class name as a command-line argument. I would probably separate the "running" from anything else:

public class Launcher {
    public static void launch(LaunchConfiguration configuration) {
        configuration.setup();
        ...
    }
}

public class LaunchConfiguration {
    public static void main(String[] args) {
        Launcher.launch(new LaunchConfiguration());
    }

    public void setup() {
    }
}

public class MyLaunchConfiguration {
    public static void main(String[] args) {
        Launcher.launch(new MyLaunchConfiguration());
    }

    @Override
    public void setup() {
    }
}

people

See more on this question at Stackoverflow