Search code examples
javainheritancesubclasssuperclass

How do you call a subclass method from a superclass in Java?


I've looked around here find an answer to my question and I can't. How do you call a subclass method from a superclass in Java?

Basically what I'm looking to do is this: I have a method called exec that takes a String as a parameter for a command. I want to be able to call the exec method in the subclass that the developer has overridden from the superclass without knowing the subclasses name ahead of time.

This is like the way the Thread class works. I'm not looking to do what every answer I've found does which is Superclass object = new Subclass(); and then just call object.method();.

This is the code in the superclass

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.text.Text;



public abstract class Console extends Application {
    private String title;
    private static Text output = new Text();


    public void create(String title) {
        this.title = title;
        launch();
    }

    public void start(Stage stage) {
        stage.setOnCloseRequest((WindowEvent event) -> {
            System.exit(0);
        });
        stage.setTitle(title);
        stage.setResizable(false);
        Group root = new Group();
        Scene scene = new Scene(root, 800, 400);
        stage.setScene(scene);
        ScrollPane scroll = new ScrollPane();
        scroll.setContent(output);
        scroll.setMaxWidth(800);
        scroll.setMaxHeight(360);
        TextField input = new TextField();
        input.setLayoutX(0);
        input.setLayoutY(380);
        input.setPrefWidth(800);
        scene.setOnKeyPressed((KeyEvent event) -> {
            if(event.getCode() == KeyCode.ENTER) {
                exec(input.getText());
                input.clear();
            }
        });
        root.getChildren().add(scroll);
        root.getChildren().add(input);
        stage.show();
    }
    public static void appendOutput(String value) {
         Platform.runLater(() -> {
            output.setText(output.getText() + "\n" + value);
        });
    }
    protected abstract void exec(String command);
}

Solution

  • The answer for my specific JavaFX subclassing question is over here Subclassing a JavaFX Application. For general subclassing the answers here are quite adequate.