AP Computer Science A

Advanced Placement Computer Science A focusing on Java programming and object-oriented design.

Advanced Topics

Inheritance and Polymorphism

Taking Code Further: Inheritance and Polymorphism

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.

How Inheritance Works

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.

Polymorphism in Action

Animal myPet = new Cat();
myPet.speak(); // Output: Meow

The program knows to call the Cat version of speak()!

Real-World Impact

  • Video games use inheritance for different types of enemies.
  • Banking apps use polymorphism for different kinds of accounts.

Tips

  • Use extends to inherit.
  • Use @Override to show when you override a method.

Examples

  • 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.

In a Nutshell

Inheritance lets you build new classes from existing ones, and polymorphism means you can write flexible code that works with many types.