I have this simple example:
public class Imap {
private Responder responder;
public Imap(){
this.responder = new Responder(this);
}
public void startService(){
responder.doStuff();
}
public boolean supportsMe(){
return true;
}
}
public class Udp {
private Responder responder;
public Udp(){
this.responder = new Responder(this);
}
public void startService(){
responder.doStuff();
}
public boolean supportsMe(){
return false;
}
}
public class Responder {
Object parent;
public Responder(Object parent){
this.parent = parent;
}
public void doStuff(){
if(parent.supportsMe()){
System.out.println("Parent supports me.");
} else {
System.out.println("Parent doesn't support me.");
}
}
}
The problem is supportsMe is undefined for Object. However, it is defined for both Udp and Imap. I would like Responder to be intelligent enough to call the right object. I believe the solution is to use Generics with Interface. I tried the following generic but still get a similar compile error (The method supportsMe() is undefined for the type T):
public class Responder<T> {
T parent;
public Responder(T parent){
this.parent = parent;
}
public void doStuff(){
if(parent.supportsMe()){
System.out.println("Parent supports me.");
} else {
System.out.println("Parent doesn't support me.");
}
}
}
Any solutions to my problem?