【问题标题】:Extending an interface in a class在类中扩展接口
【发布时间】:2016-06-30 12:42:16
【问题描述】:

我的问题或多或少是技术性的。我想做以下事情:

有一个类将同时定义默认构造函数和另一个构造函数,该构造函数将创建一个名为 NamedRunnable 的新对象。

这个类将有效地实现 Runnable 接口,因此包括它提供的 run 方法。

我想找到一种方法,不在“NamedRunnable”类本身中显式实现 run 方法,而是在所有将子类化所述类的成员中实现它。

这样的事情可能吗?

【问题讨论】:

  • 我不太清楚你想要实现什么:你想要一个构造器,它需要一个 Runnable 和 run-method 来运行这个 Runnable?
  • 你能给我们看看伪代码吗,我真的不明白你想要什么
  • 你想要这个吗? public class NamedRunnable implements Runnable {.. public void run(){}} 当然可以
  • "能够毫不费力地获得功能(.run())方法..." 实现Runnable 非常简单,有 已经没有太多的努力。

标签: java inheritance interface


【解决方案1】:

如果这是你的意思,那么是有可能的:)

public class NamedRunnable implements Runnable {
    public NamedRunnable(String name) {
        // ....
    }

    public void run() {
        // ...,
    }
}

【讨论】:

  • 感谢您的回复,但正如原始问题中所述,这是我想要避免的。相反,我将新类定义为抽象类,并让每个子类化它的类都实现 run 方法。
【解决方案2】:

听起来你想要一个实现Runnable抽象类(无法实例化):

abstract class NamedRunnable implements Runnable {
    private String name;

    protected NamedRunnable(String _name) {
        this.name = _name;
    }
}

请注意,这并没有实现runrun 在该类中是隐式抽象的,就好像你已经包含了一样

abstract public void run();

...因为我们声明了接口但没有实现它(如果没有声明类abtract,我们将不允许这样做)。

您可以将其用作具体类的基类,例如:

class Thingy extends NamedRunnable {
    public Thingy(String name) {
        super(name);
    }

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

具体类有run实现,可以实例化。

【讨论】:

  • 你甚至不需要在 NamedRunnable 中定义 run,因为它是隐式的
  • 我的意思是发布一个答案,因为我在看到实际响应之前完全按照您所说的做了,但有一个细微的区别,即在我的抽象类中将方法 run() 声明为抽象方法.
  • @Aris:最初我也是这样做的,但正如 Nicolas 上面指出的那样,没有必要,这是隐含的。无论是否在NamedRunnable 中显式键入abstract public void run();,最终结果都是相同的。
猜你喜欢
  • 2017-01-21
  • 2021-08-07
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2012-12-10
  • 1970-01-01
相关资源
最近更新 更多