Full Exam Review
Review Java fundamentals, object-oriented design, data structures, recursion, algorithms, and test-day pacing.
A lesson of AP Computer Science A, in AP CS A Exam Readiness, about 10 minutes.
Inheritance and Polymorphism
By the end of this lesson, you will be able to design class hierarchies using inheritance, override methods in subclasses, and use polymorphism to write flexible code.
Inheritance
// Superclass (parent class)
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
public void makeSound() {
System.out.println("...");
}
public String toString() {
return name + " (age " + age + ")";
}
}
// Subclass (child class)
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // calls the superclass constructor
this.breed = breed;
}
public String getBreed() { return breed; }
@Override
public void makeSound() {
System.out.println(getName() + " says: Woof!");
}
@Override
public String toString() {
return super.toString() + " - " + breed;
}
}
Inheritance: a mechanism by which a class (subclass) acquires the properties (fields) and behaviors (methods) of another class (superclass).
Keyword: extends
"Is-a" relationship: a Dog is-a Animal; a Cat is-a Animal.
super Keyword
public Dog(String name, int age, String breed) {
super(name, age); // Must be first line; calls Animal's constructor
this.breed = breed;
}
super: refers to the superclass.
super(...) in a constructor: calls the superclass constructor; must be the FIRST statement in the subclass constructor.
super.method(): calls a superclass method (especially useful in overriding).
@Override
public String toString() {
return super.toString() + ", Breed: " + breed;
}
Method Overriding
// Animal:
public void makeSound() { System.out.println("..."); }
// Dog (overrides):
@Override
public void makeSound() { System.out.println("Woof!"); }
// Cat (overrides):
@Override
public void makeSound() { System.out.println("Meow!"); }
Overriding: a subclass provides its own implementation of a method inherited from the superclass.