I have this interface,
public interface IAnything {
void m1();
void m3();
}
And two abstract classes implementing this interface:
public abstract class AbstractThing1 implements IAnything {
public void m1() {}
public void m3() {}
}
public abstract class AbstractThing2 implements IAnything {
public void m1() {}
public void m3() {}
}
Somewhere in my code I want to call a function doSomething(kindOfAbstractClass)
that perfoms m1()
and m3()
, among other jobs depending on kindOfAbstractClass.
How can I define and call doSomething()
? I did this but it is not working. Thanks
private <T extends IAnything> void doSomething(T kindOfAbstractClass) {
...
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
...
}
doSomething(AbstractThing1.class);
Your problem is that you are supplying a class type rather than an instance as parameter to doSomething
Take a look at modified code below:
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{
}
Try this:
private void doSomething(IAnything kindOfAbstractClass) {
...
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.