java - Java中重写接口(interface)方法

标签 java javafx methods interface overriding

我正在尝试使用现有的包来创建我自己的应用程序。但是我不知道如何调用接口(interface)参数化方法。

在使用JavaFX的包中,有一个类的构造函数是

public class App extends Application{
...
protected App(Logic logic) {
    this(logic.configuration().welcomeScreen, logic.configuration().name, Optional.of(logic));
}
}

界面是这样的:

public interface Logic extends X, Y {

default Configuration configuration() {
    return new Configuration(1000, "Hello world", true);
}
default void initialize() {
    System.out.println("Starting the application.");
}
}

配置如下:

public final class Configuration {
public final int tick;
public final String name;
public final boolean welcomeScreen;

public Configuration(int tick, String name, boolean welcomeScreen) {
    this.tick = tick;
    this.name = name;
    this.welcomeScreen = welcomeScreen;
}
}

应用程序的输出:

 (1000, "Hello world", true)

现在,当我创建自己的应用程序扩展时,覆盖不会通过:

public class Test extends App implements Logic{  
@Override
public Configuration configuration() {
    return new Configuration(25, "Test", true);
}

public static void main(String[] args) {

launch(args); //launches the App
}

}

输出:

(1000, "Hello world", true)

App仍然调用接口(interface)的默认方法。 这是什么原因以及在这种情况下如何绕过默认方法?

最佳答案

子类应该声明一个显式调用以下父构造函数的构造函数:

protected App(Logic logic) {
    this(logic.configuration().welcomeScreen, logic.configuration().name, Optional.of(logic));
}

否则它不会根据发布的代码进行编译...如果编译成功则意味着父类有一个无参数的构造函数。这将被隐式调用(在编译的类中),并且这不是您想要调用以使用重写的 configuration() 方法的内容。

应用程序和逻辑不应在测试中耦合。
因此,您可以引入一个类来定义 Logic 子类:

public TestLogic implements Logic{         
  @Override
  public AppConfiguration configuration() {
    return new AppConfiguration(25, "Test", true);
  }
}

并添加 Test 构造函数来传递 Logic 实例(此处为 this):

public class Test extends App {     
  public Test() {
     super(new TestLogic());
  } 
}

关于java - Java中重写接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52556020/

相关文章:

java - 如何为我的 NetBeans 模块 Maven 设置集群

java - 基本 Java 应用程序因错误退出代码而关闭

Java:访问静态方法

java - Scala,无法实现通用的java方法

java - 如何启用或禁用JavaFX表单中的按钮?

ruby - 如何将参数传递给 `[]` 的方法定义?

java - 如何在java表单标签上显示值

java - 使用 Gmail 发送电子邮件时出错

java - 具有指定分辨率的独立于平台的全屏 JFrame?

javascript - 我应该在哪里放置 javascript 和 html 代码以便通过 JavaFX 中的 Plotly.js 进行绘图?