Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nowshad-hasan/aac9db87cabc9d60d5f139c4e1af6cf2 to your computer and use it in GitHub Desktop.
Save nowshad-hasan/aac9db87cabc9d60d5f139c4e1af6cf2 to your computer and use it in GitHub Desktop.
Method overloading with polymorphic instances
public class PolymorphicMethodOverloading {
public static void main(String[] args) {
Consumer consumer = new Consumer();
Parent p1 = new Parent();
Parent p2 = new Child1();
Parent p3 = new Child2();
Child1 p4 = new Child1();
Child2 p5 = new Child2();
consumer.print(p1);
consumer.print(p2);
consumer.print(p3);
consumer.print(p4);
consumer.print(p5);
consumer.print((Child1) p2);
consumer.print((Child2) p3);
consumer.print((Parent) p4);
consumer.print((Parent) p5);
}
}
class Consumer {
void print(Child1 obj) {
System.out.println("Calling Consumer.print(Child1) :: " + obj.getClass());
}
void print(Child2 obj) {
System.out.println("Calling Consumer.print(Child2) :: " + obj.getClass());
}
void print(Parent obj) {
System.out.println("Calling Consumer.print(Parent) :: " + obj.getClass());
}
}
class Parent {
}
class Child1 extends Parent {
}
class Child2 extends Parent {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment