在 Java 中如何从超类调用子类方法? [英] How do you call a subclass method from a superclass in Java?

查看:45
本文介绍了在 Java 中如何从超类调用子类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,找到了我的问题的答案,但我找不到.在 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?

基本上我想要做的是:我有一个名为 exec 的方法,它将 String 作为命令的参数.我希望能够在不知道子类名称的情况下调用开发人员从超类覆盖的子类中的 exec 方法.

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.

这就像 Thread 类的工作方式.我不想做我找到的每个答案都做的事情,即 Superclass object = new Subclass(); 然后只调用 object.method();.

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();.

这是超类中的代码

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);
}

推荐答案

我的特定 JavaFX 子类化问题的答案在这里 继承 JavaFX 应用程序.对于一般的子类化,这里的答案已经足够了.

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

这篇关于在 Java 中如何从超类调用子类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆