Example illustrating Why Runtime Binding Must Occur for
Polymorphism to Work
Employee[] employees = new Employee[100];
Scanner scanner=new Scanner(System.in);
for(int count=0; count<100; count++)
{
System.out.println("What sort of employee (1=programmer; 2=manager)");
String typeString = scanner.nextLine();
int type=Integer.parseInt(typeString);
if(type==1)
{
// ... read in job title and favourite programming language ...
System.out.println("Programmer: enter job title");
String jobTitle=scanner.nextLine();
System.out.println("Enter favourite language:");
String favouriteLanguage=scanner.nextLine();
employees[count]=new Programmer(jobTitle,favouriteLanguage);
}
else if (type==2)
{
// ... read in job title and number of shares in the company ...
System.out.println("Manager: enter job title");
String jobTitle=scanner.nextLine();
System.out.println("Enter number of shares in company:");
int shares=Integer.parseInt(scanner.nextLine());
employees[count]=new Manager(jobTitle,shares);
}
}
for(int count=0; count<100; count++)
{
employees[count].printDetails();
}
- This example reads in a series of Employees (Programmers or Managers)
from the keyboard and stores them in an array
- The exact type of each Employee in the array is not known until the user
has chosen the employee type, which happens at run time
- The compiler cannot possibly know
which method to call as the compiler cannot tell in advance which type of Employee the
user is going to enter (obviously!)