Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Created January 19, 2014 04:56
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/8500616 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8500616 to your computer and use it in GitHub Desktop.
Compile time polymorphism example
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
*/
}
}
package polymorphism.compileTime;
public class Principal implements Worker {
public void doIt() {
System.out.println("Principal does the work");
}
}
package polymorphism.compileTime;
public class Teacher implements Worker {
public void doIt() {
System.out.println("Teacher does the work");
}
}
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