/* * TestStudent is a driver class that tests the Student * and GradStudent classes, demonstrating inheritance and polymorphism. * Don Chamberlin, March 2009 */ class TestStudent { public static void main(String[] args) { Student s1 = new Student("Peter", "Physics"); Student s2 = new Student("Michelle", "Math"); Student[] a = {s1, s2}; s2.setGpa(3.5); s2.setCoursesCompleted(); for (Student s:a) { if (s.readyToGraduate()) System.out.println(s + " is ready to graduate."); else System.out.println(s + " is not ready to graduate."); } Student s = new Student("Bill", "Politics"); GradStudent gs = new GradStudent("Hillary", "Law", "Reforming Health Care"); Student[] students = {s, gs}; for (Student ss:students) if (ss.readyToGraduate()) System.out.println(ss + " is ready."); else System.out.println(ss + " is not ready."); } // end of main() } // end of class TestStudent class Student { private String name; private String major; private double gpa; private boolean coursesCompleted; public Student(String name, String major) { this.name = name; this.major = major; this.gpa = 0.0; this.coursesCompleted = false; } public String getName() { return name; } public String getMajor() { return major; } public double getGpa() { return gpa; } public void setGpa(double gpa) { this.gpa = gpa; } public void setCoursesCompleted() { this.coursesCompleted = true; } public String toString() { return "Student " + name; } public boolean readyToGraduate() { if (gpa >= 2.0 && coursesCompleted) return true; else return false; } } // end of class Student class GradStudent extends Student { private String thesisTopic; private boolean thesisCompleted; public GradStudent(String name, String major, String topic) { super(name, major); this.thesisTopic = topic; this.thesisCompleted = false; } void setThesisCompleted() { this.thesisCompleted = true; } public String toString() { return "Grad Student " + this.getName(); } public boolean readyToGraduate() { if (super.readyToGraduate() && thesisCompleted) return true; else return false; } } // end of class GradStudent