Pregunta

Say I have a class which I want to add an attribute to. The value of this property should implement a certain interface. I do, however, not care at all what kind of object/class it is, as long as it implements the methods from a certain interface.

Is there a way to achieve this behavior?

In Objective-C, I would do it like this:

@property (nonatomic, strong) id <MyInterface> attr;
¿Fue útil?

Solución

Declare the field in your class as the type of the interface:

public class YourClass {
    private MyInterface attr;
}

It won't matter the class the object reference belongs to, it only matters if the class implements the desired interface. Here's an example:

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>());

From your comment:

I don't think of Interfaces as types. More like a feature an object has.

In Java, an interface is a type. If you want some type to have declared two interfaces at the same time, you can create a third interface that extends from both:

interface ThirdPartyInterface1 {
}

interface ThirdPartyInterface2 {
}

interface MyInterface extends ThirdPartyInterface1, ThirdPartyInterface2 {
}

public class YourClass {
    private MyInterface attr;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top