1

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?

JohnMerlino
  • 3,900
  • 4
  • 57
  • 89
  • Visitor pattern. Don't leak `this` in the constructor. Pass in the `responder` and have it visit the `parent`. – Boris the Spider Jun 27 '14 at 15:37
  • 3
    Make `Imap` and `Udp` implement some interface `Supported` which declares a `supportsMe` method. Then have `Responder` declare its `parent` field as type `Supported`. – Sotirios Delimanolis Jun 27 '14 at 15:37
  • @BoristheSpider how would this cause a memory leak? – JohnMerlino Jun 27 '14 at 15:44
  • 1
    It is not a _memory_ leak, it is a [_state_ leak](http://stackoverflow.com/a/9851843/2071828). You pass a reference to `this` before `this` actually exists. This problem can be very serious and very hard to debug. Consider if this is a parent class of a class hierarchy - none of the child ctors have yet completed. This should always be avoided. – Boris the Spider Jun 27 '14 at 15:47

0 Answers0