Last active
January 3, 2016 18:09
-
-
Save rajeevprasanna/8500647 to your computer and use it in GitHub Desktop.
Runtime polymorphism example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package polymorphism.runTime; | |
public class Principal implements Worker { | |
public void doIt() { | |
System.out.println("Principal does the work"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package polymorphism.runTime; | |
public class Teacher implements Worker { | |
public void doIt() { | |
System.out.println("Teacher does the work"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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