Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a java method based on a subclass type?

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.

like image 360
pinpinlelapin Avatar asked Jan 30 '10 22:01

pinpinlelapin


People also ask

How do you call a subclass method?

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.

How do you call a static method from a subclass?

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.

Can superclass call subclass method Java?

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

How do you call a method from another class in Java?

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.


2 Answers

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.

like image 190
Kevin Montrose Avatar answered Sep 24 '22 12:09

Kevin Montrose


So in I you declare the handler() method, and implement it appropriately (i.e. differently) in both A and B.

This is Polymorphism :)

like image 40
Noon Silk Avatar answered Sep 25 '22 12:09

Noon Silk