Programming Drill #20

Due: Monday, November 26
Goal:  See polymorphism in action

Here is a shortened version of the Person class:

public class Person
	private int age;
	private String name;

	// Default values in the default constructor
	public Person()
		age = 10;
		name = "Unknown";

	// Constructor that sets all the instance variables
	public Person(int age, String name)
		this.age = age; = name;

Here is a main class that makes an array of various objects. Recall that every class we write is automatically derived from the Object class.

public class Main
	// Output the result of the thing's toString method
	public static void OutputObject(Object thing)

	// Create an array of four random things
	// and then output each one
	public static void main(String[] args)
		Object[] things = new Object[4];

		things[0] = new Person(20, "Bobo");
		things[1] = new String("CS A201");
		things[2] = new Integer(10);
		things[3] = new Person(25, "Loco");

		// Print out each thing
		for (int i = 0; i < things.length; i++)

The main method creates an array with two Person objects, a String, and an Integer object.  For each object it invokes the OutputObject method which in turn outputs the return value of toString().  This is legal because toString() is defined within the Object class that is the parent for any class we write.

However, if you compile and run the program, it doesn't output useful information for the two Person objects.  It does output appropriate information for the String and Integer because those classes override the toString() method.  Remedy this problem by overriding the toString() method in the Person class so it returns appropriate information for a person.   The header for the toString method is:

    public String toString()


Show or email your completed program to by the end of the day.