Object Oriented Design and Development

Week 3 further reading - Polymorphism

Polymorphism

Polymorphism: an example scenario

Polymorphism Example

Runtime Binding

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();
}

Polymorphism in Method Parameters

Polymorphism in Method Parameters: Example

class Oven
{
    public void cook (Food f)
    {
        int n = f.getCookingTime();
        System.out.println("Cooking for " + n + "minutes.");
    }
}

Oven example, continued