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
...