【问题标题】:Java runnable and interfacesJava 可运行和接口
【发布时间】:2013-08-28 03:49:06
【问题描述】:

我正在尝试实现一个UserInterface 接口,它总是需要在一个线程中运行(Runnable 也是如此)。所以我有这样的代码,其中SpecificInterface 实现UserInterface

UserInterface myUI = new SpecificInterface(...);
Thread thread = new Thread(myUI);
thread.start();

但这显然行不通,因为我不能让UserInterface实现Runnable,因为接口不能实现其他接口。而且我不能只让SpecificInterface 可运行,因为这违背了使用接口的意义。

我应该如何完成这项工作?我是否需要将UserInterface 设为一个抽象类,或者创建一个实现UserInterfaceRunnableRunnableInterface 抽象类并从中继承我的UI,或者..?我很困惑为什么“简单”的解决方案行不通。

谷歌搜索没有什么帮助,我找到的只是告诉我如何使用“可运行界面”的链接:|

【问题讨论】:

  • 显示UserInterfaceSpecficInterface 类?
  • @JoshM 它们太大了,无法在此处显示。但基本上它们在run() 方法中都有一个自定义事件调度程序循环(这是为了练习)。

标签: java interface runnable


【解决方案1】:

接口可以扩展其他接口。

interface UserInterface extends Runnable {
    void someOtherFunction();
    // void run() is inherited as part of the interface specification
}

public class SpecificInterface implements UserInterface {
    @Override
    public void someOtherFunction() {
        . . .
    }

    @Override
    public void run() {
        . . .
    }
}

【讨论】:

  • UserInterface 必须是 extends Runnable。看来SpecificInterfaceUserInterface的子接口(从他的声明语句来看)。
  • @JoshM - 对不起;我的名字倒过来了。
  • 效果很好,谢谢!不知道extending 接口!
猜你喜欢
  • 1970-01-01
  • 2019-10-05
  • 2014-07-09
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多