假设我有一个接口和多个实现此接口的类:
public interface MyInterface {
public String getString();
public String getAnotherString();
}
现在我有了实现此接口的类:
public class MyClass1 implements myInterface {
@Override
public String getString() {
return "A String";
}
@Override
public String getAnotherString() {
return "foo";
}
}
和
public class MyClass2 implements myInterface {
@Override
public String getString() {
return "Another String";
}
@Override
public String getAnotherString() {
return "bar";
}
}
如何让Method接受实现myInterface
的类的对象?
public <T extends MyInterface> void aMethod(T object) {
objects.add(object); //⚡ doesn't work
}
这样可行,但它不允许我将这些对象添加到我声明的那个ArrayList中:
ArrayList<? extends MyInterface> objects = new ArrayList<>();
我做错了什么? :/
答案 0 :(得分:0)
根据的泛型?扩展MyInterface 只允许使用getter
ArrayList<? extends MyInterface> objects = new ArrayList<>();
you can only do get of type MyInterface and Object
MyInterface myInterace = objects.get(0);
Object myInterace = objects.get(0);
为了您的工作,您可以使用ArrayList<MyInterface> objects = new ArrayList<>();
现在假设如果允许添加MyInterface hade,那么通过一个简单的例子会发生什么错误
Long longValue = 20L;
List<Long> longList = new ArrayList();
longList.add(longValue);
Integer i =10;
List<? extends Number> sNumber = longList ;// longList can be assigned to ? extends Number
sNumber.add(i); // if this was allowed
longValue = longList.get(1); // we will get an exception (class cast exception)
因此编译器不允许该setter