Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Last active January 3, 2016 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeevprasanna/8500647 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8500647 to your computer and use it in GitHub Desktop.
Runtime polymorphism example
package polymorphism.runTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
//https://gist.github.com/rajeevprasanna/8500647
public class PolymorphismExample {
public static void main(String[] args) {
List workers = new ArrayList();
// Adding worker one
Worker worker1 = new Principal();
workers.add(worker1);
// Adding worker two
Worker worker2 = new Teacher();
workers.add(worker2);
for (Iterator iterator = workers.iterator(); iterator.hasNext();) {
Worker worker = (Worker) iterator.next();
worker.doIt();
}
// op : Principal does the work
// Teacher does the work
// If you see carefully, we cannot see which instance is called. We
// called doIt() method only on the Super type Worker but the JVM finds
// the proper type and called its implementation of doIt() method. This
// is Runtime Polymorphism. The JVM determines proper type only at
// runtime
}
}
package polymorphism.runTime;
public class Principal implements Worker {
public void doIt() {
System.out.println("Principal does the work");
}
}
package polymorphism.runTime;
public class Teacher implements Worker {
public void doIt() {
System.out.println("Teacher does the work");
}
}
package polymorphism.runTime;
public interface Worker {
public void doIt();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment