Reputation: 23
Recently, I have been learning about multiple dispatch in Java. I tried out an example, and I want to know if I am on the right track.
I created a parent class called Dispatch and three child classes named One, Two, and Three. In class Dispatch, I created a function called display(), which displays the class name of its arguments.
public class Dispatch {
void display(Dispatch d1, Dispatch d2){
System.out.println("Method in "+ this.getClass().getName() +" prints: "+ d1.getClass().getName()+", "+ d2.getClass().getName());
}
}
public class One extends Dispatch {
}
public class Two extends Dispatch{
}
public class Three extends Dispatch{
}
//In main function in another class, Application.java:
Dispatch one = new One();
Dispatch two = new Two();
Dispatch three = new Three();
one.display(two, three);
The output was exactly as I expected:
Method disp() in One prints: Two, Three
I just want to know if I got the concept of multiple dispatch right, or if this is merely an inaccurate workaround. Thanks in advance.
Upvotes: 1
Views: 191
Reputation: 304
Yuu don't need toString functions in each of those classes. This code will do your job
void display(Dispatch d1, Dispatch d2){
System.out.println("Method in "+ this.getClass().getName() +" prints: "+ d1.getClass().getName()+", "+ d2.getClass().getName());
}
Upvotes: 1