1

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.

1
  • Your question might be better suited for Code Review (though read their question guidelines first). Commented Mar 27, 2019 at 16:04

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. I noted this down. So apart from this, did I implement multiple dispatch well? Am I conceptually right?
Yes. You have understood inheritance and polymorphisim

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.