University of Toronto - Fall 2000
Department of Computer Science

Week 11 - Polymorphism

Polymorphism example

Let's suppose that as well as Person and its child class Student, we also have a child class Employee. Employees are Persons with a salary, which will be included in the String returned by getInfo(). Write the Employee class:

	class Employee extends                {
		

		public Employee (String n,String b, int s) {
			
			
		}

		public int getSalary() {

		}

		public String getInfo() {
			




		}
	}

Which getInfo method would be called in the following code?

	Person p = new Student ("Ed", "1982", "0910");
	System.out.println (p.getInfo());
	p = new Employee ("Al", "1978", 50000);
	System.out.println (p.getInfo());
	p = new Person ("Sue", "1955");
	System.out.println (p.getInfo());

Another Inheritance Example - Mark classes

class LetterGrade extends Mark {
	private String mark;

	public LetterGrade (String mark) {
		this.mark = mark;
	}

	public int intValue () {
		if (mark.equals("A+")) return 95;
		if (mark.equals("A")) return 88;
		...
	}
}

class PercentGrade extends Mark {
	private int mark;

	public PercentGrade (String mark) {
		this.mark = Integer.parseInt(mark);
	}

	public int intValue () {
		return mark;
	}
}

We also need a class Mark for these to be extensions of:

class Mark {
	public int intValue () {
		return -9999; // We're hoping the student will
			// complain if this mark is used!
	}
}

Mark is the parent class or super class. LetterGrade and PercentGrade are child classes or sub classes.

Let's use these classes in our main( ). First, build the Vector markList by putting this code into a loop:

	System.out.print("letter grade? ");
	Mark mk;
	if (in.readLine().equals("y")) {
		mk = new LetterGrade(in.readLine());
	} else {
		mk = new PercentGrade(in.readLine());
	}
	markList.addElement(mk);

Then to find the average:

	int sum = 0;
	for (int i = 0; i < markList.size(); i++) {
		Mark mk = (Mark)markList.elementAt(i);
		sum += mk.intValue();		// polymorphism!
	}
	System.out.println ("Average is " + (double)sum/markList.size());