Inheritance
Objective #1: Explain how inheritance can be used to develop a child class from a parent class.
public class Person { private int myAge;If you want to build a Student class which has an additional myGrade property (as in grade level like 9th grade, 10th grade, etc.) as well as setGrade, getGrade, passExams, and saySomething public methods, then you can "extend" the Person class in this way:
public Person() { myAge = 0; } public void setAge(int age) { myAge = age; } public int getAge() { return myAge; } public void haveBirthday() { myAge++; } public void saySomething() { System.out.println("I am a person"); } }
public class Student extends Person { private int myGrade;
public Student() { myGrade = 9; }
public void setGrade(int grade) { myGrade = grade; }
public int getGrade() { return myGrade; } public void passExams() { myGrade++; }
public void saySomething() { System.out.println("I am a student"); } }
If you want to build an APStudent class which has an additional myAPExamScore property (as in a number between 1 and 5) as well as setAPExamScore, getAPExamScore, studyForExam, saySomething, compareTo, toString, and equals public methods, then you can "extend" the Student class in this way:
public class APStudent extends Student implements Comparable { private int myAPExamScore;
public APStudent() { myAPExamScore = 3; } public void setAPExamScore(int apExamScore) { myAPExamScore = apExamScore; } public int getAPExamScore() { return myAPExamScore; } public void studyForExam() { if (myAPExamScore < 5) { myAPExamScore++; } } public void saySomething() { System.out.println("I am an AP student"); } public int compareTo(Object other) { return getAPExamScore() - ((APStudent) other).getAPExamScore()); } public String toString() { return "myAPExamScore = " + myAPExamScore; } public boolean equals(Object other) { if (myAPExamScore == ((APStudent) other).myAPExamScore) { return true; } return false; } }
Objective #2: Explain how a child class object can be referenced (i.e. "cloaked") as its parent class data type.
Objective #3: Be able to override methods from a parent class and add new methods to a child class.
Objective #4: Invoke inherited methods.
Objective #5: Invoke superclass constructors.
Objective #6: Override its toString and equals methods from the Object superclass.
Objective #7: Explain protected access control. NOT REALLY STRESSED ON AP EXAM.