假设我有
public interface MyInterface {
public void aMethod();
}
public class MyClass implements MyInterface {
@Override
public void aMethod() {
Log.d("aMethod");
}
}
我想声明一个实现MyInterface的对象,所以我可以在构造函数中实例化它,如下所示
public class AnotherClass {
Class <? extends MyInterface> mObjectThatImplements;
public AnotherClass() {
// Says it cannot convert MyClass to Class <? extends MyInterface>
mObjectThatImplements = new MyClass();
}
}
答案 0 :(得分:4)
您只需更改声明类型即可。将其作为接口,您可以为其分配任何实现。
public class AnotherClass {
MyInterface mObjectThatImplements;
public AnotherClass() {
mObjectThatImplements = new MyClass();
}
}