2013-08-28 62 views
0

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

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

但是,这显然是行不通的,因为我不能让UserInterface实现Runnable因为接口无法实现其他接口。我不能只让SpecificInterface可以运行,因为这会破坏使用接口的点。

我该如何做这项工作?我是否需要将UserInterface设为抽象类,或创建一个RunnableInterface抽象类,它实现了UserInterfaceRunnable并从中继承我的UI,或者?我很困惑,为什么“简单”的解决方案无法工作。

谷歌搜索不太有用,我找到的是告诉我如何使用“Runnable接口”的链接:

+0

显示'UserInterface'和'SpecficInterface'类? –

+0

@JoshM他们太大而无法在这里展示。但基本上它们都在'run()'方法中有一个自定义事件调度器循环(这是一个练习)。 – Thomas

回答

3

接口可以扩展其他接口。

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() { 
     . . . 
    } 
} 
+0

'UserInterface'必须'扩展''Runnable'。看起来'SpecificInterface'是'UserInterface'的子接口(从他的声明声明来看)。 –

+0

@JoshM - 对不起;我的名字倒退了。 –

+0

这很好,谢谢!不知道'扩展'接口! – Thomas