我有这个界面,
public interface IAnything {
void m1();
void m3();
}
实现此接口的两个抽象类:
public abstract class AbstractThing1 implements IAnything {
public void m1() {}
public void m3() {}
}
public abstract class AbstractThing2 implements IAnything {
public void m1() {}
public void m3() {}
}
在我的代码中的某个地方,我想调用一个function doSomething(kindOfAbstractClass)
来执行m1()
和m3()
,以及取决于kindOfAbstractClass的其他工作。
如何定义和调用doSomething()
?我做了这个,但它没有用。感谢
private <T extends IAnything> void doSomething(T kindOfAbstractClass) {
...
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
...
}
doSomething(AbstractThing1.class);
答案 0 :(得分:4)
您的问题是您正在提供类类型而不是实例作为doSomething的参数
看看下面修改过的代码:
public class MyClass {
void doIt(){
doSomething(new ConcreteThing());
}
private <T extends IAnything> void doSomething(T kindOfAbstractClass) {
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
}
}
interface IAnything {
void m1();
void m3();
}
abstract class AbstractThing1 implements IAnything {
public void m1() {}
public void m3() {}
}
class ConcreteThing extends AbstractThing1{
}
答案 1 :(得分:3)
试试这个:
private void doSomething(IAnything kindOfAbstractClass) {
...
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
...
}