Advanced Placement Computer Science A focusing on Java programming and object-oriented design.
In Java, you can create new classes that build on existing ones—this is called inheritance. It helps you avoid repeating code. Polymorphism lets you treat objects of different classes in the same way if they share a common ancestor.
public class Animal {
void speak() {
System.out.println("Animal makes a sound");
}
}
public class Cat extends Animal {
void speak() {
System.out.println("Meow");
}
}
Here, Cat
inherits from Animal
but can override the speak()
method.
Animal myPet = new Cat();
myPet.speak(); // Output: Meow
The program knows to call the Cat
version of speak()
!
extends
to inherit.@Override
to show when you override a method.A Truck
class extends a Vehicle
class, adding cargo capacity.
A Shape
superclass with subclasses like Circle
and Rectangle
that each have a draw()
method.
Inheritance lets you build new classes from existing ones, and polymorphism means you can write flexible code that works with many types.