AP Computer Science A — Unit 9 Review: Inheritance, Polymorphism & Constructors
Animal
).Tiger
extends Animal
).extends
keyword declares a subclass:java
class Animal { ... }
class Tiger extends Animal { ... }
* Java classes that omit extends
implicitly extend Object
.
* Single inheritance: one direct superclass; multiple subclasses allowed.
* protected
, public
members inherited; private
are not (but exist, accessible via superclass methods).
private
instance methods from superclass.class Worker {
public void doWork() { ... }
private void earnMinWage() { ... }
}
class Tradesperson extends Worker {
// inherits doWork(), not earnMinWage()
public void doSkilledWork() { ... }
}
@Override
(optional but recommended).@Override
public void doWork() {
// subclass-specific behavior
}
super
Keywordsuper.method()
calls the version in the immediate superclass (bypasses override).super(args)
in a constructor calls a superclass constructor (must be first line).class Car {
public void applyBrakes() { ... }
public void checkSurroundings() { ... }
}
class SelfDrivingCar extends Car {
@Override
public void applyBrakes() { ... }
public void emergencyOverride() {
super.applyBrakes(); // Car's version
checkSurroundings(); // current class's override
}
}
private
fields is not allowed.class Animal {
private int numLegs;
public int getNumLegs() { return numLegs; }
}
class Bird extends Animal {
public void report() {
System.out.println(getNumLegs());
}
}
Animal a = new Lion(); // can call Animal's methods
Animal b = new Bat(); // same reference type
// a.run(); // ❌ if run() is only in Mammal
a.sleep(); // ✔ inherited from Animal, overridden in Lion if exists
java
Animal[] zoo = { new Lion(), new Dragon(), new Bat() };
for(Animal x : zoo) x.eat();
// dynamic dispatch calls each subclass's eat()
super(...)
) or default no-arg if no explicit call.class Vehicle {
public Vehicle(String type) { ... }
}
class Airplane extends Vehicle {
public Airplane(String type, int seats) {
super(type); // call Vehicle(String)
this.seats = seats;
}
}
super(...)
.public class Robot {
public Robot() { ... }
public Robot(String name) { this.name = name; }
public Robot(String name, int id) { this(name); this.id = id; }
}
extends
defines inheritance; super
accesses parent behavior.@Override
.super(...)
and/or this(...)
; default provided only if none written.private
not inherited; use superclass-provided accessors.Master these concepts to design and leverage class hierarchies effectively in your AP CSA projects and exam answers!