【问题标题】:Java attribute which implements a certain Interface实现某个接口的 Java 属性
【发布时间】:2014-05-09 13:52:54
【问题描述】:

假设我有一个要添加属性的类。该属性的值应该实现某个接口。但是,我完全不在乎它是什么类型的对象/类,只要它实现了某个接口的方法即可。

有没有办法实现这种行为?

在 Objective-C 中,我会这样做:

@property (nonatomic, strong) id <MyInterface> attr;

【问题讨论】:

  • &lt;modifier&gt; MyInterface attr;

标签: java interface attributes


【解决方案1】:

将类中的字段声明为接口的类型:

public class YourClass {
    private MyInterface attr;
}

对象引用所属的类无关紧要,重要的是该类实现了所需的接口。这是一个例子:

public class MyClass {
    private List<String> stringList;
    public void setStringList(List<String> stringList) {
        this.stringList = stringList;
    }
}

//...
MyClass myClass = new MyClass();
myClass.setStringList(new ArrayList<String>());
myClass.setStringList(new LinkedList<String>());

来自您的评论:

我不认为接口是类型。更像是一个对象所具有的特征。

在 Java 中,接口是一种类型。如果您希望某个类型同时声明两个接口,您可以创建从这两个接口扩展的第三个接口:

interface ThirdPartyInterface1 {
}

interface ThirdPartyInterface2 {
}

interface MyInterface extends ThirdPartyInterface1, ThirdPartyInterface2 {
}

public class YourClass {
    private MyInterface attr;
}

【讨论】:

  • 谢谢!如果它必须实现多个接口怎么办?
  • @Jenox 变量声明为单一类型。
  • @Jenox 你只能使用一个界面。确保其他接口从顶级接口扩展。
  • @DaveNewton 我不认为接口是类型。更像是一个对象所具有的特征。显然它可以有多个。在 Objective-C 中我会做&lt;Interface1, Interface&gt;。你是在告诉我这在 Java 中是不可能的吗?
  • @Jenox 可能用于 Objective C,但在 Java 中接口是类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 2017-06-29
  • 1970-01-01
相关资源
最近更新 更多