Skip to the content.

Unit 9 Notes

Unit 9: Inheritance – AP Computer Science A

🔑 Key Concepts

  • extends keyword for inheritance
  • Superclass and subclass relationships
  • Method overriding
  • Using super to call parent constructors/methods
  • Polymorphism basics

🧬 Inheritance Hierarchy

Inheritance allows a subclass to inherit fields and methods from a superclass.

public class Animal {
    public void speak() {
        System.out.println("Generic sound");
    }
}

public class Dog extends Animal {
    public void speak() {
        System.out.println("Woof");
    }
}

📌 Overriding Methods

A subclass can override methods from its superclass.

@Override
public void speak() {
    System.out.println("Bark!");
}
  • Must have same name, return type, and parameters
  • Optional @Override annotation helps catch errors

🧩 Calling Superclass Methods

Use super.methodName() to call the parent’s version:

public class Puppy extends Dog {
    public void speak() {
        super.speak(); // calls Dog's speak
        System.out.println("Yip!");
    }
}

🧱 Calling Superclass Constructors

Use super() to call parent constructor (must be first line):

public class Dog extends Animal {
    public Dog() {
        super(); // calls Animal constructor
    }
}

🌀 Polymorphism (Intro)

A superclass reference can point to a subclass object:

Animal a = new Dog();
a.speak(); // calls Dog's speak method
  • Java uses the object type (not reference type) to decide which method to run

🧪 Practice Multiple Choice (5 Questions)

1. What is inheritance?
(A) Repeating code in every class
(B) Creating methods in a loop
(C) Using one class to base another on
(D) Sharing variables between methods
Answer: (C)


2. What does the super keyword do?
(A) Creates a new object
(B) Refers to the parent class
(C) Imports a library
(D) Stops inheritance
Answer: (B)


3. What will this print?

class A {
    public void hello() {
        System.out.println("A");
    }
}
class B extends A {
    public void hello() {
        System.out.println("B");
    }
}
A obj = new B();
obj.hello();

(A) A
(B) B
(C) AB
(D) Error
Answer: (B)


4. What must be true to override a method?
(A) Same name, different return type
(B) Same name, same parameters
(C) New parameters
(D) Private visibility
Answer: (B)


5. Why use @Override?
(A) It’s required
(B) Adds security
(C) Helps catch mistakes when overriding
(D) Makes code run faster
Answer: (C)