public class PersonStudentTest { /** * Tests the Person and Student classes */ public static void main(String[] args) { Person p = new Person("Sara", 25); p.speak(); Student s = new Student("Huy", 27, 3.9); s.speak(); Person q = s; // type conformance rule q.speak(); // calls speak in Student -> dynamic binding // Any variable has two types // static type: defined when the variable is declared // For instance, the static type of q is Person. // dynamic type: the type of the object that the variable // refers to // For q, the dynamic type is Student // the static type never changes. The dynamic type may // change. // Create an array of Person objects (some of the elements // may be Student objects) Person[] a = new Person[5]; String[] names = {"Tanya", "Bobby", "Mauricio", "Xiwei", "Polar"}; for (int i = 0; i < a.length; i ++) { int age = (int) (Math.random() * 10) + 20; if (Math.random() < 0.5) { // person a[i] = new Person(names[i], age); } else { // student double gpa = 3.5 + 0.5 * Math.random(); a[i] = new Student(names[i], age, gpa); } } // Call speak for each element of a for (Person e: a) { e.speak(); } } }