0

I have interface A and, extending from it classes AB, AC and AD. I call a method giving me A (actually an instance of AB, AC, or AD). I have created following code:

private parse(A arg){
    throw new NotSupportedException("We don't support:" + arg.getClass());
}

private parse(AB arg){
    //do something
}
private parse(AC arg){
    //do something
}

private void doStuff(){
    parse(somethingThatReturnsSomeInstanceOfA());
}

The idea is, that I need to do different things based on the actual type I have. I have no control over these interfaces, so I can't move my parse methods there. I wanted to leverage Java behaviour of choosing the most specific overloaded method. You'll note that I don't have a method for AD - I don't want to implement specific behaviour for all extending interfaces, hence the method accepting A throwing exception.

That however doesn't work. Even when getClass() returns AB when calling parse() I always end up in parse(A). Why? And is there a way to fix it? I don't want to do a lot of ifs and instanceofs...

Deltharis
  • 2,320
  • 1
  • 18
  • 29
  • How are those instances declared? – Makoto Sep 20 '18 at 15:53
  • 3
    I suspect that `somethingThatReturnsSomeInstanceOfA()` has a return type `A` and thus all the JVM knows is that `parse(A)` needs to get called. – Thomas Sep 20 '18 at 15:54
  • 1
    That's what I'm thinking too @Thomas but I wanted to be sure. – Makoto Sep 20 '18 at 15:54
  • Related question: https://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type – Adam Sep 20 '18 at 15:55
  • 1
    You need double dispatch aka Visitor pattern: https://www.google.com/search?q=double+dispatch+java&rlz=1C1GCEA_enUS790US790&oq=double+dispatch+&aqs=chrome.1.69i57j0l5.4438j0j7&sourceid=chrome&ie=UTF-8 – duffymo Sep 20 '18 at 15:55

0 Answers0