I'm trying to dispatch objects to separate method according to their subclass.
For instance, consider those 2 objects
class A extends I {}
class B extends I {}
and the method
void dispatch(I i) {}
in dispatch()
, I'd like to invoke a method according to the type of i
. Hence if i
is actually of type A, the handlerA(A a)
method will be called. If it's of type B, handlerB(B b)
will be called, and so on ... I tried with method overloading but I guess it doesn't work this way
what is the best way to achieve this ? I'd like to avoid using if/else statement ...
Thanks in advance,
edit: I can't modify any of those classes.
You can override these methods in SubB1 or SubB2 to get a different behavior but to get to a "new" method defined in SubB1 you must declare an object of type SubB1. Cast obj to be of the type SubB1. Then you can call your subclass methods.
A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name.
Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).
In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.
Use the Visitor Pattern.
In short, have I
declare an accept(Visitor<T> ...)
method, and have Visitor
expose onA(A ...)
, onB(B ...)
, etc. methods. Your implementations of the I
interface will call the appropriate method on the passed in Visitor<T>
.
Its probably not worth it (due to boilerplate) if you only have 2 concrete classes, but somewhere around 3 or 4 it starts being worth it - if just to avoid duplicated if-else constructs.
So in I
you declare the handler()
method, and implement it appropriately (i.e. differently) in both A
and B
.
This is Polymorphism :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With