AP Computer Science A

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

Advanced Topics

Inheritance and Polymorphism

Building on Code: Inheritance

Inheritance lets one class use the fields and methods of another. It's like a family tree for your code!

public class Animal {
  void eat() {
    System.out.println("Yum!");
  }
}

public class Cat extends Animal {
  void meow() {
    System.out.println("Meow!");
  }
}

Here, Cat inherits from Animal, so Cat objects can both eat() and meow().

Polymorphism: Many Forms, One Interface

Polymorphism allows you to write code that works with objects of different classes in a uniform way.

Animal pet = new Cat();
pet.eat(); // Works!

If a method exists in the parent class, any child class can use or override it.

Benefits

  • Reduces code duplication
  • Makes programs easier to expand

Real-World Analogy

Think of a "Vehicle" class. Cars, bikes, and buses all inherit from it but behave in their own unique ways.

Examples

  • A Teacher class inherits from a Person class and adds a teach() method.

  • Using a Shape parent class so both Circle and Rectangle can be used in the same drawing method.

In a Nutshell

Inheritance shares code; polymorphism lets objects act in different ways.

Key Terms

Inheritance
A mechanism where one class acquires properties and behaviors of another.
Polymorphism
The ability of objects to take on many forms, usually by sharing a common interface.