Created
January 19, 2014 04:56
-
-
Save rajeevprasanna/8500616 to your computer and use it in GitHub Desktop.
Compile time 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.compileTime; | |
public class PolymorphismExample { | |
public void doSomething(Worker worker) { | |
System.out.println("I'm a worker"); | |
} | |
public void doSomething(Teacher teacher) { | |
System.out.println("I'm a Teacher"); | |
} | |
public void doSomething(Principal principal) { | |
System.out.println("I'm a Principal"); | |
} | |
public static void main(String[] args) { | |
PolymorphismExample example = new PolymorphismExample(); | |
Worker principal = new Principal(); | |
Worker teacher = new Teacher(); | |
example.doSomething(principal); | |
example.doSomething(teacher); | |
/* | |
* You would expect the output as bellow, If you run the | |
* PolymorphismExample class | |
* | |
* I'm a Principal I'm a Teacher | |
* | |
* WRONG, the actual output will be | |
* | |
* I'm a worker I'm a worker | |
* | |
* Here the type is decided at compile time. Even though the objects are | |
* instances of Principal and Teacher, the reference is a Worker type. | |
* So the compiler picks the doSomething(Worker worker) method as it | |
* accepts the same type of reference type | |
*/ | |
} | |
} |
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.compileTime; | |
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.compileTime; | |
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.compileTime; | |
public interface Worker { | |
public void doIt(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment