You have Employee, Manager, and Developer classes. They share fields like name and salary. Instead of duplicating code, inheritance lets Manager and Developer extend Employee, inheriting its fields and methods while adding their own.

Basic inheritance

Create a subclass that extends a parent class.

example
Basic.java
Replay: real traced execution (multi-file project)
// Basic Inheritance

public class Basic {
    public static void main(String[] args) {
        System.out.println("=== Basic Inheritance ===\n");

        // Create a Dog object
        Dog dog = new Dog();
        String dogName = "Buddy";
        dog.name = dogName;

        // Dog has its own method
        dog.bark();

        // Dog inherits from Animal
        dog.eat();
        dog.sleep();

        System.out.println("\n=== Accessing Inherited Fields ===");

        // Inherited field
        System.out.println("Dog's name: " + dog.name);
        System.out.println("Dog's age: " + dog.age);

        System.out.println("\n=== Cat Example ===");

        Cat cat = new Cat();
        String catName = "Whiskers";
        cat.name = catName;
        cat.meow();
        cat.eat();    // Inherited
        cat.sleep();  // Inherited
    }
}

// Parent class (superclass)
class Animal {
    String name;
    int age;

    void eat() {
        System.out.println(name + " is eating");
    }

    void sleep() {
        System.out.println(name + " is sleeping");
    }
}

// Child class (subclass)
class Dog extends Animal {
    // Dog-specific method
    void bark() {
        System.out.println(name + " says: Woof!");
    }
}

// Another child class
class Cat extends Animal {
    void meow() {
        System.out.println(name + " says: Meow!");
    }
}

// Basic Inheritance

public class Basic {
    public static void main(String[] args) {
        System.out.println("=== Basic Inheritance ===\n");

        // Create a Dog object
        Dog dog = new Dog();
        String dogName = "Luna";
        dog.name = dogName;

        // Dog has its own method
        dog.bark();

        // Dog inherits from Animal
        dog.eat();
        dog.sleep();

        System.out.println("\n=== Accessing Inherited Fields ===");

        // Inherited field
        System.out.println("Dog's name: " + dog.name);
        System.out.println("Dog's age: " + dog.age);

        System.out.println("\n=== Cat Example ===");

        Cat cat = new Cat();
        String catName = "Whiskers";
        cat.name = catName;
        cat.meow();
        cat.eat();    // Inherited
        cat.sleep();  // Inherited
    }
}

// Parent class (superclass)
class Animal {
    String name;
    int age;

    void eat() {
        System.out.println(name + " is eating");
    }

    void sleep() {
        System.out.println(name + " is sleeping");
    }
}

// Child class (subclass)
class Dog extends Animal {
    // Dog-specific method
    void bark() {
        System.out.println(name + " says: Woof!");
    }
}

// Another child class
class Cat extends Animal {
    void meow() {
        System.out.println(name + " says: Meow!");
    }
}

// Basic Inheritance

public class Basic {
    public static void main(String[] args) {
        System.out.println("=== Basic Inheritance ===\n");

        // Create a Dog object
        Dog dog = new Dog();
        String dogName = "Rex";
        dog.name = dogName;

        // Dog has its own method
        dog.bark();

        // Dog inherits from Animal
        dog.eat();
        dog.sleep();

        System.out.println("\n=== Accessing Inherited Fields ===");

        // Inherited field
        System.out.println("Dog's name: " + dog.name);
        System.out.println("Dog's age: " + dog.age);

        System.out.println("\n=== Cat Example ===");

        Cat cat = new Cat();
        String catName = "Whiskers";
        cat.name = catName;
        cat.meow();
        cat.eat();    // Inherited
        cat.sleep();  // Inherited
    }
}

// Parent class (superclass)
class Animal {
    String name;
    int age;

    void eat() {
        System.out.println(name + " is eating");
    }

    void sleep() {
        System.out.println(name + " is sleeping");
    }
}

// Child class (subclass)
class Dog extends Animal {
    // Dog-specific method
    void bark() {
        System.out.println(name + " says: Woof!");
    }
}

// Another child class
class Cat extends Animal {
    void meow() {
        System.out.println(name + " says: Meow!");
    }
}

// Basic Inheritance

public class Basic {
    public static void main(String[] args) {
        System.out.println("=== Basic Inheritance ===\n");

        // Create a Dog object
        Dog dog = new Dog();
        String dogName = "Buddy";
        dog.name = dogName;

        // Dog has its own method
        dog.bark();

        // Dog inherits from Animal
        dog.eat();
        dog.sleep();

        System.out.println("\n=== Accessing Inherited Fields ===");

        // Inherited field
        System.out.println("Dog's name: " + dog.name);
        System.out.println("Dog's age: " + dog.age);

        System.out.println("\n=== Cat Example ===");

        Cat cat = new Cat();
        String catName = "Misty";
        cat.name = catName;
        cat.meow();
        cat.eat();    // Inherited
        cat.sleep();  // Inherited
    }
}

// Parent class (superclass)
class Animal {
    String name;
    int age;

    void eat() {
        System.out.println(name + " is eating");
    }

    void sleep() {
        System.out.println(name + " is sleeping");
    }
}

// Child class (subclass)
class Dog extends Animal {
    // Dog-specific method
    void bark() {
        System.out.println(name + " says: Woof!");
    }
}

// Another child class
class Cat extends Animal {
    void meow() {
        System.out.println(name + " says: Meow!");
    }
}

// Basic Inheritance

public class Basic {
    public static void main(String[] args) {
        System.out.println("=== Basic Inheritance ===\n");

        // Create a Dog object
        Dog dog = new Dog();
        String dogName = "Buddy";
        dog.name = dogName;

        // Dog has its own method
        dog.bark();

        // Dog inherits from Animal
        dog.eat();
        dog.sleep();

        System.out.println("\n=== Accessing Inherited Fields ===");

        // Inherited field
        System.out.println("Dog's name: " + dog.name);
        System.out.println("Dog's age: " + dog.age);

        System.out.println("\n=== Cat Example ===");

        Cat cat = new Cat();
        String catName = "Shadow";
        cat.name = catName;
        cat.meow();
        cat.eat();    // Inherited
        cat.sleep();  // Inherited
    }
}

// Parent class (superclass)
class Animal {
    String name;
    int age;

    void eat() {
        System.out.println(name + " is eating");
    }

    void sleep() {
        System.out.println(name + " is sleeping");
    }
}

// Child class (subclass)
class Dog extends Animal {
    // Dog-specific method
    void bark() {
        System.out.println(name + " says: Woof!");
    }
}

// Another child class
class Cat extends Animal {
    void meow() {
        System.out.println(name + " says: Meow!");
    }
}

  1. dog ← ⟨Dog A⟩, dogName ← Buddy, dog.name ← Buddy

    3public class Basic {4    public static void main(String[] args) {5        System.out.println("=== Basic Inheritance ===\n");6        7        // Create a Dog object  //?createdog8        Dog dog→ ⟨Dog A⟩ = new Dog();9        String dogName→ Buddy = "Buddy";  //@dogName="Luna", "Rex"10        dog.name→ Buddy = dogNameBuddy;11        12        // Dog has its own method  //?ownmethod13        dog.bark();
    output=== Basic Inheritance ===
  2. void bark()

    12        // Dog has its own method  //?ownmethod13        dog.bark();14        15        // Dog inherits from Animal  //?inherited16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field  //?inheritedfield22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();  //?cat28        String catName = "Whiskers";  //@catName="Misty", "Shadow"29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)  //?superclass37class Animal {38    String name;  //?parentfield39    int age;40    41    void eat() {  //?parentmethod42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)  //?subclass51class Dog extends Animal {  //?extends52    // Dog-specific method53    void bark() {  //?childmethod54        System.out.println(nameBuddy + " says: Woof!");55    }
    outputBuddy says: Woof!
  3. void eat()

    pass 1 of 2
    15        // Dog inherits from Animal  //?inherited16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field  //?inheritedfield22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();  //?cat28        String catName = "Whiskers";  //@catName="Misty", "Shadow"29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)  //?superclass37class Animal {38    String name;  //?parentfield39    int age;40    41    void eat() {  //?parentmethod42        System.out.println(nameBuddy + " is eating");43    }
    outputBuddy is eating
  4. cat ← ⟨Cat B⟩, catName ← Whiskers, cat.name ← Whiskers

    pass 1 of 2
    16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field  //?inheritedfield22        System.out.println("Dog's name: " + dog.nameBuddy);23        System.out.println("Dog's age: " + dog.age0);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat→ ⟨Cat B⟩ = new Cat();  //?cat28        String catName→ Whiskers = "Whiskers";  //@catName="Misty", "Shadow"29        cat.name→ Whiskers = catNameWhiskers;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)  //?superclass37class Animal {38    String name;  //?parentfield39    int age;40    41    void eat() {  //?parentmethod42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameBuddy + " is sleeping");47    }
    outputBuddy is sleeping
    
    === Accessing Inherited Fields ===
    Dog's name: Buddy
    Dog's age: 0
    
    === Cat Example ===
  5. void meow()

    29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)  //?superclass37class Animal {38    String name;  //?parentfield39    int age;40    41    void eat() {  //?parentmethod42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)  //?subclass51class Dog extends Animal {  //?extends52    // Dog-specific method53    void bark() {  //?childmethod54        System.out.println(name + " says: Woof!");55    }56}5758// Another child class59class Cat extends Animal {60    void meow() {61        System.out.println(nameWhiskers + " says: Meow!");62    }
    outputWhiskers says: Meow!
  6. void eat()

    pass 2 of 2
    30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)  //?superclass37class Animal {38    String name;  //?parentfield39    int age;40    41    void eat() {  //?parentmethod42        System.out.println(nameWhiskers + " is eating");43    }
    outputWhiskers is eating
  7. void sleep()

    pass 2 of 2
    31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)  //?superclass37class Animal {38    String name;  //?parentfield39    int age;40    41    void eat() {  //?parentmethod42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameWhiskers + " is sleeping");47    }
    outputWhiskers is sleeping
  1. dog ← ⟨Dog A⟩, dogName ← Luna, dog.name ← Luna

    3public class Basic {4    public static void main(String[] args) {5        System.out.println("=== Basic Inheritance ===\n");6        7        // Create a Dog object8        Dog dog→ ⟨Dog A⟩ = new Dog();9        String dogName→ Luna = "Luna";10        dog.name→ Luna = dogNameLuna;11        12        // Dog has its own method13        dog.bark();
    output=== Basic Inheritance ===
  2. void bark()

    12        // Dog has its own method13        dog.bark();14        15        // Dog inherits from Animal16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();28        String catName = "Whiskers";29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)51class Dog extends Animal {52    // Dog-specific method53    void bark() {54        System.out.println(nameLuna + " says: Woof!");55    }
    outputLuna says: Woof!
  3. void eat()

    pass 1 of 2
    15        // Dog inherits from Animal16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();28        String catName = "Whiskers";29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(nameLuna + " is eating");43    }
    outputLuna is eating
  4. cat ← ⟨Cat B⟩, catName ← Whiskers, cat.name ← Whiskers

    pass 1 of 2
    16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.nameLuna);23        System.out.println("Dog's age: " + dog.age0);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat→ ⟨Cat B⟩ = new Cat();28        String catName→ Whiskers = "Whiskers";29        cat.name→ Whiskers = catNameWhiskers;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameLuna + " is sleeping");47    }
    outputLuna is sleeping
    
    === Accessing Inherited Fields ===
    Dog's name: Luna
    Dog's age: 0
    
    === Cat Example ===
  5. void meow()

    29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)51class Dog extends Animal {52    // Dog-specific method53    void bark() {54        System.out.println(name + " says: Woof!");55    }56}5758// Another child class59class Cat extends Animal {60    void meow() {61        System.out.println(nameWhiskers + " says: Meow!");62    }
    outputWhiskers says: Meow!
  6. void eat()

    pass 2 of 2
    30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(nameWhiskers + " is eating");43    }
    outputWhiskers is eating
  7. void sleep()

    pass 2 of 2
    31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameWhiskers + " is sleeping");47    }
    outputWhiskers is sleeping
  1. dog ← ⟨Dog A⟩, dogName ← Rex, dog.name ← Rex

    3public class Basic {4    public static void main(String[] args) {5        System.out.println("=== Basic Inheritance ===\n");6        7        // Create a Dog object8        Dog dog→ ⟨Dog A⟩ = new Dog();9        String dogName→ Rex = "Rex";10        dog.name→ Rex = dogNameRex;11        12        // Dog has its own method13        dog.bark();
    output=== Basic Inheritance ===
  2. void bark()

    12        // Dog has its own method13        dog.bark();14        15        // Dog inherits from Animal16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();28        String catName = "Whiskers";29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)51class Dog extends Animal {52    // Dog-specific method53    void bark() {54        System.out.println(nameRex + " says: Woof!");55    }
    outputRex says: Woof!
  3. void eat()

    pass 1 of 2
    15        // Dog inherits from Animal16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();28        String catName = "Whiskers";29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(nameRex + " is eating");43    }
    outputRex is eating
  4. cat ← ⟨Cat B⟩, catName ← Whiskers, cat.name ← Whiskers

    pass 1 of 2
    16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.nameRex);23        System.out.println("Dog's age: " + dog.age0);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat→ ⟨Cat B⟩ = new Cat();28        String catName→ Whiskers = "Whiskers";29        cat.name→ Whiskers = catNameWhiskers;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameRex + " is sleeping");47    }
    outputRex is sleeping
    
    === Accessing Inherited Fields ===
    Dog's name: Rex
    Dog's age: 0
    
    === Cat Example ===
  5. void meow()

    29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)51class Dog extends Animal {52    // Dog-specific method53    void bark() {54        System.out.println(name + " says: Woof!");55    }56}5758// Another child class59class Cat extends Animal {60    void meow() {61        System.out.println(nameWhiskers + " says: Meow!");62    }
    outputWhiskers says: Meow!
  6. void eat()

    pass 2 of 2
    30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(nameWhiskers + " is eating");43    }
    outputWhiskers is eating
  7. void sleep()

    pass 2 of 2
    31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameWhiskers + " is sleeping");47    }
    outputWhiskers is sleeping
  1. dog ← ⟨Dog A⟩, dogName ← Buddy, dog.name ← Buddy

    3public class Basic {4    public static void main(String[] args) {5        System.out.println("=== Basic Inheritance ===\n");6        7        // Create a Dog object8        Dog dog→ ⟨Dog A⟩ = new Dog();9        String dogName→ Buddy = "Buddy";10        dog.name→ Buddy = dogNameBuddy;11        12        // Dog has its own method13        dog.bark();
    output=== Basic Inheritance ===
  2. void bark()

    12        // Dog has its own method13        dog.bark();14        15        // Dog inherits from Animal16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();28        String catName = "Misty";29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)51class Dog extends Animal {52    // Dog-specific method53    void bark() {54        System.out.println(nameBuddy + " says: Woof!");55    }
    outputBuddy says: Woof!
  3. void eat()

    pass 1 of 2
    15        // Dog inherits from Animal16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();28        String catName = "Misty";29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(nameBuddy + " is eating");43    }
    outputBuddy is eating
  4. cat ← ⟨Cat B⟩, catName ← Misty, cat.name ← Misty

    pass 1 of 2
    16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.nameBuddy);23        System.out.println("Dog's age: " + dog.age0);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat→ ⟨Cat B⟩ = new Cat();28        String catName→ Misty = "Misty";29        cat.name→ Misty = catNameMisty;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameBuddy + " is sleeping");47    }
    outputBuddy is sleeping
    
    === Accessing Inherited Fields ===
    Dog's name: Buddy
    Dog's age: 0
    
    === Cat Example ===
  5. void meow()

    29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)51class Dog extends Animal {52    // Dog-specific method53    void bark() {54        System.out.println(name + " says: Woof!");55    }56}5758// Another child class59class Cat extends Animal {60    void meow() {61        System.out.println(nameMisty + " says: Meow!");62    }
    outputMisty says: Meow!
  6. void eat()

    pass 2 of 2
    30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(nameMisty + " is eating");43    }
    outputMisty is eating
  7. void sleep()

    pass 2 of 2
    31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameMisty + " is sleeping");47    }
    outputMisty is sleeping
  1. dog ← ⟨Dog A⟩, dogName ← Buddy, dog.name ← Buddy

    3public class Basic {4    public static void main(String[] args) {5        System.out.println("=== Basic Inheritance ===\n");6        7        // Create a Dog object8        Dog dog→ ⟨Dog A⟩ = new Dog();9        String dogName→ Buddy = "Buddy";10        dog.name→ Buddy = dogNameBuddy;11        12        // Dog has its own method13        dog.bark();
    output=== Basic Inheritance ===
  2. void bark()

    12        // Dog has its own method13        dog.bark();14        15        // Dog inherits from Animal16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();28        String catName = "Shadow";29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)51class Dog extends Animal {52    // Dog-specific method53    void bark() {54        System.out.println(nameBuddy + " says: Woof!");55    }
    outputBuddy says: Woof!
  3. void eat()

    pass 1 of 2
    15        // Dog inherits from Animal16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.name);23        System.out.println("Dog's age: " + dog.age);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat = new Cat();28        String catName = "Shadow";29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(nameBuddy + " is eating");43    }
    outputBuddy is eating
  4. cat ← ⟨Cat B⟩, catName ← Shadow, cat.name ← Shadow

    pass 1 of 2
    16        dog.eat();17        dog.sleep();18        19        System.out.println("\n=== Accessing Inherited Fields ===");20        21        // Inherited field22        System.out.println("Dog's name: " + dog.nameBuddy);23        System.out.println("Dog's age: " + dog.age0);24        25        System.out.println("\n=== Cat Example ===");26        27        Cat cat→ ⟨Cat B⟩ = new Cat();28        String catName→ Shadow = "Shadow";29        cat.name→ Shadow = catNameShadow;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameBuddy + " is sleeping");47    }
    outputBuddy is sleeping
    
    === Accessing Inherited Fields ===
    Dog's name: Buddy
    Dog's age: 0
    
    === Cat Example ===
  5. void meow()

    29        cat.name = catName;30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(name + " is sleeping");47    }48}4950// Child class (subclass)51class Dog extends Animal {52    // Dog-specific method53    void bark() {54        System.out.println(name + " says: Woof!");55    }56}5758// Another child class59class Cat extends Animal {60    void meow() {61        System.out.println(nameShadow + " says: Meow!");62    }
    outputShadow says: Meow!
  6. void eat()

    pass 2 of 2
    30        cat.meow();31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(nameShadow + " is eating");43    }
    outputShadow is eating
  7. void sleep()

    pass 2 of 2
    31        cat.eat();    // Inherited32        cat.sleep();  // Inherited33    }34}3536// Parent class (superclass)37class Animal {38    String name;39    int age;40    41    void eat() {42        System.out.println(name + " is eating");43    }44    45    void sleep() {46        System.out.println(nameShadow + " is sleeping");47    }
    outputShadow is sleeping

class Child extends Parent inherits all non-private members from Parent.

extends Inherit from a class: `class Dog extends Animal`. Dog gets Animal's fields and methods.

Call parent constructor

Initialize parent class fields with super().

SuperConstructor.java
Replay: real traced execution (multi-file project)
// Calling Parent Constructor with super()

public class SuperConstructor {
    public static void main(String[] args) {
        System.out.println("=== super() Constructor Call ===\n");

        // Create Employee
        Employee emp = new Employee("Alice", 30);
        emp.displayInfo();

        System.out.println("\n=== Manager (extends Employee) ===");

        // Create Manager
        Manager mgr = new Manager("Bob", 45, "Engineering");
        mgr.displayInfo();

        System.out.println("\n=== Developer (extends Employee) ===");

        Developer dev = new Developer("Carol", 28, "Java");
        dev.displayInfo();

        System.out.println("\n=== Constructor Call Order ===");

        System.out.println("Creating new Manager...");
        Manager mgr2 = new Manager("Dan", 35, "Sales");
    }
}

// Parent class
class Person {
    String name;
    int age;

    Person(String name, int age) {
        System.out.println("  Person constructor called");
        this.name = name;
        this.age = age;
    }
}

// Child class
class Employee extends Person {
    int employeeId;
    static int nextId = 1000;

    Employee(String name, int age) {
        super(name, age);
        System.out.println("  Employee constructor called");
        this.employeeId = nextId++;
    }

    void displayInfo() {
        System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);
    }
}

// Grandchild class
class Manager extends Employee {
    String department;

    Manager(String name, int age, String department) {
        super(name, age);
        System.out.println("  Manager constructor called");
        this.department = department;
    }

    @Override
    void displayInfo() {
        System.out.println("Manager: " + name + ", Age: " + age +
                          ", ID: " + employeeId + ", Dept: " + department);
    }
}

class Developer extends Employee {
    String language;

    Developer(String name, int age, String language) {
        super(name, age);  // Calls Employee constructor
        this.language = language;
    }

    @Override
    void displayInfo() {
        System.out.println("Developer: " + name + ", Age: " + age +
                          ", ID: " + employeeId + ", Lang: " + language);
    }
}

  1. public static void main(String[] args)

    3public class SuperConstructor {4    public static void main(String[] args) {5        System.out.println("=== super() Constructor Call ===\n");6        7        // Create Employee  //?createemp8        Employee emp = new Employee("Alice", 30);9        emp.displayInfo();
    output=== super() Constructor Call ===
  2. this.name ← Alice, this.age ← 30

    pass 1 of 4
    34Person(String nameAlice, int age30) {  //?personconstructor35    System.out.println("  Person constructor called");36    this.name→ Alice = nameAlice;37    this.age→ 30 = age30;38}
    output  Person constructor called
    All 4 passes — pass 1 is the card above
    passnameageemployeeIddepartmentlanguagethis.namethis.agethis.departmentmgrthis.languagedevmgr2
    1Alice301000Alice30
    2Bob451001EngineeringBob45Engineering⟨Manager A⟩
    3Carol281002JavaCarol28Java⟨Developer B⟩
    4Dan35SalesDan35Sales⟨Manager C⟩
  3. nextId ← 1001, this.employeeId ← 1000, emp ← ⟨Employee D⟩

    pass 1 of 4
    7        // Create Employee  //?createemp8        Employee emp→ ⟨Employee D⟩ = new Employee("Alice", 30);9        emp.displayInfo();10        11        System.out.println("\n=== Manager (extends Employee) ===");12        13        // Create Manager  //?createmgr14        Manager mgr = new Manager("Bob", 45, "Engineering");15        mgr.displayInfo();16        17        System.out.println("\n=== Developer (extends Employee) ===");18        19        Developer dev = new Developer("Carol", 28, "Java");  //?createdev20        dev.displayInfo();21        22        System.out.println("\n=== Constructor Call Order ===");23        24        System.out.println("Creating new Manager...");25        Manager mgr2 = new Manager("Dan", 35, "Sales");  //?order26    }27}2829// Parent class30class Person {31    String name;32    int age;33    34    Person(String name, int age) {  //?personconstructor35        System.out.println("  Person constructor called");36        this.name = name;37        this.age = age;38    }39}4041// Child class42class Employee extends Person {43    int employeeId;44    static int nextId = 1000;45    46    Employee(String nameAlice, int age30) {  //?empconstructor47        super(name, age);  //?supercall48        System.out.println("  Employee constructor called");49        this.employeeId→ 1000 = nextId→ 1001++;50    }
    output  Employee constructor called
    All 4 passes — pass 1 is the card above
    passnameageemployeeIddepartmentlanguagenextIdthis.employeeIdempthis.departmentmgrthis.languagedevmgr2
    1Alice3010001000 10011000⟨Employee D⟩
    2Bob451001Engineering1001 10021001Engineering⟨Manager A⟩
    3Carol281002Java1002 10031002Java⟨Developer B⟩
    4Dan35Sales1003 10041003Sales⟨Manager C⟩
  4. void displayInfo()

    8        Employee emp = new Employee("Alice", 30);9        emp.displayInfo();10        11        System.out.println("\n=== Manager (extends Employee) ===");12        13        // Create Manager  //?createmgr14        Manager mgr = new Manager("Bob", 45, "Engineering");15        mgr.displayInfo();16        17        System.out.println("\n=== Developer (extends Employee) ===");18        19        Developer dev = new Developer("Carol", 28, "Java");  //?createdev20        dev.displayInfo();21        22        System.out.println("\n=== Constructor Call Order ===");23        24        System.out.println("Creating new Manager...");25        Manager mgr2 = new Manager("Dan", 35, "Sales");  //?order26    }27}2829// Parent class30class Person {31    String name;32    int age;33    34    Person(String name, int age) {  //?personconstructor35        System.out.println("  Person constructor called");36        this.name = name;37        this.age = age;38    }39}4041// Child class42class Employee extends Person {43    int employeeId;44    static int nextId = 1000;45    46    Employee(String name, int age) {  //?empconstructor47        super(name, age);  //?supercall48        System.out.println("  Employee constructor called");49        this.employeeId = nextId++;50    }51    52    void displayInfo() {53        System.out.println("Employee: " + nameAlice + ", Age: " + age30 + ", ID: " + employeeId1000);54    }
    outputEmployee: Alice, Age: 30, ID: 1000
    
    === Manager (extends Employee) ===
  5. this.department ← Engineering, mgr ← ⟨Manager A⟩

    pass 1 of 2
    13        // Create Manager  //?createmgr14        Manager mgr→ ⟨Manager A⟩ = new Manager("Bob", 45, "Engineering");15        mgr.displayInfo();16        17        System.out.println("\n=== Developer (extends Employee) ===");18        19        Developer dev = new Developer("Carol", 28, "Java");  //?createdev20        dev.displayInfo();21        22        System.out.println("\n=== Constructor Call Order ===");23        24        System.out.println("Creating new Manager...");25        Manager mgr2 = new Manager("Dan", 35, "Sales");  //?order26    }27}2829// Parent class30class Person {31    String name;32    int age;33    34    Person(String name, int age) {  //?personconstructor35        System.out.println("  Person constructor called");36        this.name = name;37        this.age = age;38    }39}4041// Child class42class Employee extends Person {43    int employeeId;44    static int nextId = 1000;45    46    Employee(String name, int age) {  //?empconstructor47        super(name, age);  //?supercall48        System.out.println("  Employee constructor called");49        this.employeeId = nextId++;50    }51    52    void displayInfo() {53        System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54    }55}5657// Grandchild class58class Manager extends Employee {59    String department;60    61    Manager(String nameBob, int age45, String departmentEngineering) {  //?mgrconstructor62        super(name, age);  //?superemployee63        System.out.println("  Manager constructor called");64        this.department→ Engineering = departmentEngineering;65    }
    output  Manager constructor called
  6. @Override void displayInfo()

    14        Manager mgr = new Manager("Bob", 45, "Engineering");15        mgr.displayInfo();16        17        System.out.println("\n=== Developer (extends Employee) ===");18        19        Developer dev = new Developer("Carol", 28, "Java");  //?createdev20        dev.displayInfo();21        22        System.out.println("\n=== Constructor Call Order ===");23        24        System.out.println("Creating new Manager...");25        Manager mgr2 = new Manager("Dan", 35, "Sales");  //?order26    }27}2829// Parent class30class Person {31    String name;32    int age;33    34    Person(String name, int age) {  //?personconstructor35        System.out.println("  Person constructor called");36        this.name = name;37        this.age = age;38    }39}4041// Child class42class Employee extends Person {43    int employeeId;44    static int nextId = 1000;45    46    Employee(String name, int age) {  //?empconstructor47        super(name, age);  //?supercall48        System.out.println("  Employee constructor called");49        this.employeeId = nextId++;50    }51    52    void displayInfo() {53        System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54    }55}5657// Grandchild class58class Manager extends Employee {59    String department;60    61    Manager(String name, int age, String department) {  //?mgrconstructor62        super(name, age);  //?superemployee63        System.out.println("  Manager constructor called");64        this.department = department;65    }66    67    @Override68    void displayInfo() {69        System.out.println("Manager: " + nameBob + ", Age: " + age45 + 70                          ", ID: " + employeeId1001 + ", Dept: " + departmentEngineering);71    }
    outputManager: Bob, Age: 45, ID: 1001, Dept: Engineering
    
    === Developer (extends Employee) ===
  7. this.language ← Java, dev ← ⟨Developer B⟩

    19        Developer dev→ ⟨Developer B⟩ = new Developer("Carol", 28, "Java");  //?createdev20        dev.displayInfo();21        22        System.out.println("\n=== Constructor Call Order ===");23        24        System.out.println("Creating new Manager...");25        Manager mgr2 = new Manager("Dan", 35, "Sales");  //?order26    }27}2829// Parent class30class Person {31    String name;32    int age;33    34    Person(String name, int age) {  //?personconstructor35        System.out.println("  Person constructor called");36        this.name = name;37        this.age = age;38    }39}4041// Child class42class Employee extends Person {43    int employeeId;44    static int nextId = 1000;45    46    Employee(String name, int age) {  //?empconstructor47        super(name, age);  //?supercall48        System.out.println("  Employee constructor called");49        this.employeeId = nextId++;50    }51    52    void displayInfo() {53        System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54    }55}5657// Grandchild class58class Manager extends Employee {59    String department;60    61    Manager(String name, int age, String department) {  //?mgrconstructor62        super(name, age);  //?superemployee63        System.out.println("  Manager constructor called");64        this.department = department;65    }66    67    @Override68    void displayInfo() {69        System.out.println("Manager: " + name + ", Age: " + age + 70                          ", ID: " + employeeId + ", Dept: " + department);71    }72}7374class Developer extends Employee {75    String language;76    77    Developer(String nameCarol, int age28, String languageJava) {  //?devconstructor78        super(name, age);  // Calls Employee constructor79        this.language→ Java = languageJava;80    }
  8. @Override void displayInfo()

    19        Developer dev = new Developer("Carol", 28, "Java");  //?createdev20        dev.displayInfo();21        22        System.out.println("\n=== Constructor Call Order ===");23        24        System.out.println("Creating new Manager...");25        Manager mgr2 = new Manager("Dan", 35, "Sales");  //?order26    }27}2829// Parent class30class Person {31    String name;32    int age;33    34    Person(String name, int age) {  //?personconstructor35        System.out.println("  Person constructor called");36        this.name = name;37        this.age = age;38    }39}4041// Child class42class Employee extends Person {43    int employeeId;44    static int nextId = 1000;45    46    Employee(String name, int age) {  //?empconstructor47        super(name, age);  //?supercall48        System.out.println("  Employee constructor called");49        this.employeeId = nextId++;50    }51    52    void displayInfo() {53        System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54    }55}5657// Grandchild class58class Manager extends Employee {59    String department;60    61    Manager(String name, int age, String department) {  //?mgrconstructor62        super(name, age);  //?superemployee63        System.out.println("  Manager constructor called");64        this.department = department;65    }66    67    @Override68    void displayInfo() {69        System.out.println("Manager: " + name + ", Age: " + age + 70                          ", ID: " + employeeId + ", Dept: " + department);71    }72}7374class Developer extends Employee {75    String language;76    77    Developer(String name, int age, String language) {  //?devconstructor78        super(name, age);  // Calls Employee constructor79        this.language = language;80    }81    82    @Override83    void displayInfo() {84        System.out.println("Developer: " + nameCarol + ", Age: " + age28 + 85                          ", ID: " + employeeId1002 + ", Lang: " + languageJava);86    }
    outputDeveloper: Carol, Age: 28, ID: 1002, Lang: Java
    
    === Constructor Call Order ===
    Creating new Manager...
  9. this.department ← Sales, mgr2 ← ⟨Manager C⟩

    pass 2 of 2
    24        System.out.println("Creating new Manager...");25        Manager mgr2→ ⟨Manager C⟩ = new Manager("Dan", 35, "Sales");  //?order26    }27}2829// Parent class30class Person {31    String name;32    int age;33    34    Person(String name, int age) {  //?personconstructor35        System.out.println("  Person constructor called");36        this.name = name;37        this.age = age;38    }39}4041// Child class42class Employee extends Person {43    int employeeId;44    static int nextId = 1000;45    46    Employee(String name, int age) {  //?empconstructor47        super(name, age);  //?supercall48        System.out.println("  Employee constructor called");49        this.employeeId = nextId++;50    }51    52    void displayInfo() {53        System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54    }55}5657// Grandchild class58class Manager extends Employee {59    String department;60    61    Manager(String nameDan, int age35, String departmentSales) {  //?mgrconstructor62        super(name, age);  //?superemployee63        System.out.println("  Manager constructor called");64        this.department→ Sales = departmentSales;65    }
    output  Manager constructor called

super(args) calls parent constructor. Must be first statement.

super Reference to parent class. `super()` calls constructor, `super.method()` calls method.

Override parent methods

Replace parent behavior in subclass.

MethodOverride.java
Replay: real traced execution (multi-file project)
// Method Overriding

public class MethodOverride {
    public static void main(String[] args) {
        System.out.println("=== Method Overriding ===\n");

        Animal animal = new Animal("Generic Animal");
        animal.makeSound();
        animal.move();

        System.out.println("\n=== Dog Override ===");

        Dog dog = new Dog("Buddy");
        dog.makeSound();  // Overridden
        dog.move();       // Inherited (not overridden)

        System.out.println("\n=== Bird Override ===");

        Bird bird = new Bird("Tweety");
        bird.makeSound();  // Overridden
        bird.move();       // Overridden

        System.out.println("\n=== Calling Parent Method with super ===");

        Cat cat = new Cat("Whiskers");
        cat.makeSound();
    }
}

class Animal {
    String name;

    Animal(String name) {
        this.name = name;
    }

    void makeSound() {
        System.out.println(name + " makes a sound");
    }

    void move() {
        System.out.println(name + " moves around");
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name);
    }

    @Override
    void makeSound() {
        System.out.println(name + " barks: Woof! Woof!");
    }
    // move() is inherited as-is
}

class Bird extends Animal {
    Bird(String name) {
        super(name);
    }

    @Override
    void makeSound() {
        System.out.println(name + " chirps: Tweet! Tweet!");
    }

    @Override
    void move() {
        System.out.println(name + " flies through the air");
    }
}

class Cat extends Animal {
    Cat(String name) {
        super(name);
    }

    @Override
    void makeSound() {
        super.makeSound();
        System.out.println(name + " also meows: Meow!");
    }
}

  1. public static void main(String[] args)

    3public class MethodOverride {4    public static void main(String[] args) {5        System.out.println("=== Method Overriding ===\n");6        7        Animal animal = new Animal("Generic Animal");  //?createanimal8        animal.makeSound();
    output=== Method Overriding ===
  2. this.name ← Generic Animal, animal ← ⟨Animal A⟩

    pass 1 of 4
    7        Animal animal→ ⟨Animal A⟩ = new Animal("Generic Animal");  //?createanimal8        animal.makeSound();9        animal.move();10        11        System.out.println("\n=== Dog Override ===");12        13        Dog dog = new Dog("Buddy");  //?createdog14        dog.makeSound();  // Overridden  //?calloverride15        dog.move();       // Inherited (not overridden)16        17        System.out.println("\n=== Bird Override ===");18        19        Bird bird = new Bird("Tweety");20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String nameGeneric Animal) {34        this.name→ Generic Animal = nameGeneric Animal;35    }
    All 4 passes — pass 1 is the card above
    passnamethis.nameanimaldogbirdcat
    1Generic AnimalGeneric Animal⟨Animal A⟩
    2BuddyBuddy⟨Dog B⟩
    3TweetyTweety⟨Bird C⟩
    4WhiskersWhiskers⟨Cat D⟩
  3. void makeSound()

    pass 1 of 2
    7        Animal animal = new Animal("Generic Animal");  //?createanimal8        animal.makeSound();9        animal.move();10        11        System.out.println("\n=== Dog Override ===");12        13        Dog dog = new Dog("Buddy");  //?createdog14        dog.makeSound();  // Overridden  //?calloverride15        dog.move();       // Inherited (not overridden)16        17        System.out.println("\n=== Bird Override ===");18        19        Bird bird = new Bird("Tweety");20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(nameGeneric Animal + " makes a sound");39    }
    outputGeneric Animal makes a sound
  4. void move()

    pass 1 of 2
    8        animal.makeSound();9        animal.move();10        11        System.out.println("\n=== Dog Override ===");12        13        Dog dog = new Dog("Buddy");  //?createdog14        dog.makeSound();  // Overridden  //?calloverride15        dog.move();       // Inherited (not overridden)16        17        System.out.println("\n=== Bird Override ===");18        19        Bird bird = new Bird("Tweety");20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(nameGeneric Animal + " moves around");43    }
    outputGeneric Animal moves around
    
    === Dog Override ===
  5. dog ← ⟨Dog B⟩

    13        Dog dog→ ⟨Dog B⟩ = new Dog("Buddy");  //?createdog14        dog.makeSound();  // Overridden  //?calloverride15        dog.move();       // Inherited (not overridden)16        17        System.out.println("\n=== Bird Override ===");18        19        Bird bird = new Bird("Tweety");20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(name + " moves around");43    }44}4546class Dog extends Animal {47    Dog(String nameBuddy) {48        super(name);
  6. @Override //?override void makeSound()

    13        Dog dog = new Dog("Buddy");  //?createdog14        dog.makeSound();  // Overridden  //?calloverride15        dog.move();       // Inherited (not overridden)16        17        System.out.println("\n=== Bird Override ===");18        19        Bird bird = new Bird("Tweety");20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(name + " moves around");43    }44}4546class Dog extends Animal {47    Dog(String name) {48        super(name);49    }50    51    @Override  //?override52    void makeSound() {  //?dogmakesound53        System.out.println(nameBuddy + " barks: Woof! Woof!");54    }
    outputBuddy barks: Woof! Woof!
  7. void move()

    pass 2 of 2
    14        dog.makeSound();  // Overridden  //?calloverride15        dog.move();       // Inherited (not overridden)16        17        System.out.println("\n=== Bird Override ===");18        19        Bird bird = new Bird("Tweety");20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(nameBuddy + " moves around");43    }
    outputBuddy moves around
    
    === Bird Override ===
  8. bird ← ⟨Bird C⟩

    19        Bird bird→ ⟨Bird C⟩ = new Bird("Tweety");20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(name + " moves around");43    }44}4546class Dog extends Animal {47    Dog(String name) {48        super(name);49    }50    51    @Override  //?override52    void makeSound() {  //?dogmakesound53        System.out.println(name + " barks: Woof! Woof!");54    }55    // move() is inherited as-is56}5758class Bird extends Animal {59    Bird(String nameTweety) {60        super(name);
  9. @Override void makeSound()

    19        Bird bird = new Bird("Tweety");20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(name + " moves around");43    }44}4546class Dog extends Animal {47    Dog(String name) {48        super(name);49    }50    51    @Override  //?override52    void makeSound() {  //?dogmakesound53        System.out.println(name + " barks: Woof! Woof!");54    }55    // move() is inherited as-is56}5758class Bird extends Animal {59    Bird(String name) {60        super(name);61    }62    63    @Override64    void makeSound() {65        System.out.println(nameTweety + " chirps: Tweet! Tweet!");66    }
    outputTweety chirps: Tweet! Tweet!
  10. @Override void move()

    20        bird.makeSound();  // Overridden21        bird.move();       // Overridden  //?birdmove22        23        System.out.println("\n=== Calling Parent Method with super ===");24        25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(name + " moves around");43    }44}4546class Dog extends Animal {47    Dog(String name) {48        super(name);49    }50    51    @Override  //?override52    void makeSound() {  //?dogmakesound53        System.out.println(name + " barks: Woof! Woof!");54    }55    // move() is inherited as-is56}5758class Bird extends Animal {59    Bird(String name) {60        super(name);61    }62    63    @Override64    void makeSound() {65        System.out.println(name + " chirps: Tweet! Tweet!");66    }67    68    @Override69    void move() {  //?birdoverride70        System.out.println(nameTweety + " flies through the air");71    }
    outputTweety flies through the air
    
    === Calling Parent Method with super ===
  11. cat ← ⟨Cat D⟩

    25        Cat cat→ ⟨Cat D⟩ = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(name + " moves around");43    }44}4546class Dog extends Animal {47    Dog(String name) {48        super(name);49    }50    51    @Override  //?override52    void makeSound() {  //?dogmakesound53        System.out.println(name + " barks: Woof! Woof!");54    }55    // move() is inherited as-is56}5758class Bird extends Animal {59    Bird(String name) {60        super(name);61    }62    63    @Override64    void makeSound() {65        System.out.println(name + " chirps: Tweet! Tweet!");66    }67    68    @Override69    void move() {  //?birdoverride70        System.out.println(name + " flies through the air");71    }72}7374class Cat extends Animal {75    Cat(String nameWhiskers) {76        super(name);
  12. void makeSound()

    pass 2 of 2
    37void makeSound() {  //?parentmakesound38    System.out.println(nameWhiskers + " makes a sound");39}
    outputWhiskers makes a sound
  13. System.out.println(name + " also meows: Meow!");

    25        Cat cat = new Cat("Whiskers");26        cat.makeSound();  //?supermethod27    }28}2930class Animal {31    String name;32    33    Animal(String name) {34        this.name = name;35    }36    37    void makeSound() {  //?parentmakesound38        System.out.println(name + " makes a sound");39    }40    41    void move() {42        System.out.println(name + " moves around");43    }44}4546class Dog extends Animal {47    Dog(String name) {48        super(name);49    }50    51    @Override  //?override52    void makeSound() {  //?dogmakesound53        System.out.println(name + " barks: Woof! Woof!");54    }55    // move() is inherited as-is56}5758class Bird extends Animal {59    Bird(String name) {60        super(name);61    }62    63    @Override64    void makeSound() {65        System.out.println(name + " chirps: Tweet! Tweet!");66    }67    68    @Override69    void move() {  //?birdoverride70        System.out.println(name + " flies through the air");71    }72}7374class Cat extends Animal {75    Cat(String name) {76        super(name);77    }78    79    @Override80    void makeSound() {81        super.makeSound();  //?superdot82        System.out.println(nameWhiskers + " also meows: Meow!");83    }
    outputWhiskers also meows: Meow!

Same signature in subclass replaces parent method. Use @Override annotation.

override Subclass provides its own version of parent method. Same name and parameters.

Protected access

Share members with subclasses but not the world.

Protected.java
Replay: real traced execution (multi-file project)
// Protected Access Modifier

public class Protected {
    public static void main(String[] args) {
        System.out.println("=== Protected Access ===\n");

        // Create BankAccount
        BankAccount account = new BankAccount("Alice", 1000);
        account.displayInfo();

        System.out.println("\n=== SavingsAccount (child) ===");

        SavingsAccount savings = new SavingsAccount("Bob", 5000, 0.03);
        savings.displayInfo();
        savings.addInterest();
        savings.displayInfo();

        System.out.println("\n=== Access Levels Demo ===");

        System.out.println("""
        Access Modifiers in Inheritance:

        | Modifier   | Same Class | Subclass | Other Classes |
        |------------|------------|----------|---------------|
        | private    | Yes        | No       | No            |
        | (default)  | Yes        | Yes*     | Yes*          |
        | protected  | Yes        | Yes      | No            |
        | public     | Yes        | Yes      | Yes           |

        * Same package only
        """);
    }
}

class BankAccount {
    private String accountNumber;
    protected String ownerName;
    protected double balance;

    public BankAccount(String owner, double initialBalance) {
        this.accountNumber = generateAccountNumber();
        this.ownerName = owner;
        this.balance = initialBalance;
    }

    private String generateAccountNumber() {
        return "ACC" + System.currentTimeMillis() % 10000;
    }

    protected void updateBalance(double amount) {
        this.balance += amount;
        System.out.println("Balance updated by: " + amount);
    }

    public void displayInfo() {
        System.out.println("Account: " + accountNumber);
        System.out.println("Owner: " + ownerName);
        System.out.println("Balance: $" + balance);
    }
}

class SavingsAccount extends BankAccount {
    private double interestRate;

    public SavingsAccount(String owner, double initialBalance, double rate) {
        super(owner, initialBalance);
        this.interestRate = rate;
    }

    public void addInterest() {
        // Can access protected field 'balance'
        double interest = balance * interestRate;

        // Can call protected method
        updateBalance(interest);

        // Can access protected field 'ownerName'
        System.out.println("Interest added for " + ownerName);

        // Cannot access private 'accountNumber'!
        // System.out.println(accountNumber);  // ERROR!
    }
}

  1. public static void main(String[] args)

    3public class Protected {4    public static void main(String[] args) {5        System.out.println("=== Protected Access ===\n");6        7        // Create BankAccount  //?createaccount8        BankAccount account = new BankAccount("Alice", 1000);9        account.displayInfo();
    output=== Protected Access ===
  2. public BankAccount(String owner, double initialBalance)

    pass 1 of 2
    40public BankAccount(String ownerAlice, double initialBalance1000.0) {41    this.accountNumber = generateAccountNumber();42    this.ownerName = owner;
  3. this.accountNumber ← ACC4895, this.ownerName ← Alice, this.balance ← 1000.0

    7        // Create BankAccount  //?createaccount8        BankAccount account→ ⟨BankAccount A⟩ = new BankAccount("Alice", 1000);9        account.displayInfo();10        11        System.out.println("\n=== SavingsAccount (child) ===");12        13        SavingsAccount savings = new SavingsAccount("Bob", 5000, 0.03);  //?createsavings14        savings.displayInfo();15        savings.addInterest();  //?addinterest16        savings.displayInfo();17        18        System.out.println("\n=== Access Levels Demo ===");19        20        System.out.println("""21        Access Modifiers in Inheritance:22        23        | Modifier   | Same Class | Subclass | Other Classes |24        |------------|------------|----------|---------------|25        | private    | Yes        | No       | No            |26        | (default)  | Yes        | Yes*     | Yes*          |27        | protected  | Yes        | Yes      | No            |28        | public     | Yes        | Yes      | Yes           |29        30        * Same package only31        """);32    }33}3435class BankAccount {36    private String accountNumber;  //?privatefield37    protected String ownerName;    //?protectedfield38    protected double balance;      //?protectedbalance39    40    public BankAccount(String owner, double initialBalance) {41        this.accountNumber→ ACC4895 = generateAccountNumber();42        this.ownerName→ Alice = ownerAlice;43        this.balance→ 1000.0 = initialBalance1000.0;44    }
  4. public void displayInfo()

    pass 1 of 3
    8        BankAccount account = new BankAccount("Alice", 1000);9        account.displayInfo();10        11        System.out.println("\n=== SavingsAccount (child) ===");12        13        SavingsAccount savings = new SavingsAccount("Bob", 5000, 0.03);  //?createsavings14        savings.displayInfo();15        savings.addInterest();  //?addinterest16        savings.displayInfo();17        18        System.out.println("\n=== Access Levels Demo ===");19        20        System.out.println("""21        Access Modifiers in Inheritance:22        23        | Modifier   | Same Class | Subclass | Other Classes |24        |------------|------------|----------|---------------|25        | private    | Yes        | No       | No            |26        | (default)  | Yes        | Yes*     | Yes*          |27        | protected  | Yes        | Yes      | No            |28        | public     | Yes        | Yes      | Yes           |29        30        * Same package only31        """);32    }33}3435class BankAccount {36    private String accountNumber;  //?privatefield37    protected String ownerName;    //?protectedfield38    protected double balance;      //?protectedbalance39    40    public BankAccount(String owner, double initialBalance) {41        this.accountNumber = generateAccountNumber();42        this.ownerName = owner;43        this.balance = initialBalance;44    }45    46    private String generateAccountNumber() {  //?privatemethod47        return "ACC" + System.currentTimeMillis() % 10000;48    }49    50    protected void updateBalance(double amount) {  //?protectedmethod51        this.balance += amount;52        System.out.println("Balance updated by: " + amount);53    }54    55    public void displayInfo() {56        System.out.println("Account: " + accountNumberACC4895);57        System.out.println("Owner: " + ownerNameAlice);58        System.out.println("Balance: $" + balance1000.0);59    }
    outputAccount: ACC4895
    Owner: Alice
    Balance: $1000.0
    
    === SavingsAccount (child) ===
    All 3 passes — pass 1 is the card above
    passaccountNumberownerNamebalanceownerinitialBalanceinterestRateamountinterestthis.balance
    1ACC4895Alice1000.0Bob5000.0
    2ACC4899Bob5000.00.03150.0150.05000.0 5150.0
    3ACC4899Bob5150.0
  5. public BankAccount(String owner, double initialBalance)

    pass 2 of 2
    40public BankAccount(String ownerBob, double initialBalance5000.0) {41    this.accountNumber = generateAccountNumber();42    this.ownerName = owner;
  6. this.accountNumber ← ACC4899, this.ownerName ← Bob, this.balance ← 5000.0

    40public BankAccount(String owner, double initialBalance) {41    this.accountNumber→ ACC4899 = generateAccountNumber();42    this.ownerName→ Bob = ownerBob;43    this.balance→ 5000.0 = initialBalance5000.0;44}
  7. this.interestRate ← 0.03, savings ← ⟨SavingsAccount B⟩

    13        SavingsAccount savings→ ⟨SavingsAccount B⟩ = new SavingsAccount("Bob", 5000, 0.03);  //?createsavings14        savings.displayInfo();15        savings.addInterest();  //?addinterest16        savings.displayInfo();17        18        System.out.println("\n=== Access Levels Demo ===");19        20        System.out.println("""21        Access Modifiers in Inheritance:22        23        | Modifier   | Same Class | Subclass | Other Classes |24        |------------|------------|----------|---------------|25        | private    | Yes        | No       | No            |26        | (default)  | Yes        | Yes*     | Yes*          |27        | protected  | Yes        | Yes      | No            |28        | public     | Yes        | Yes      | Yes           |29        30        * Same package only31        """);32    }33}3435class BankAccount {36    private String accountNumber;  //?privatefield37    protected String ownerName;    //?protectedfield38    protected double balance;      //?protectedbalance39    40    public BankAccount(String owner, double initialBalance) {41        this.accountNumber = generateAccountNumber();42        this.ownerName = owner;43        this.balance = initialBalance;44    }45    46    private String generateAccountNumber() {  //?privatemethod47        return "ACC" + System.currentTimeMillis() % 10000;48    }49    50    protected void updateBalance(double amount) {  //?protectedmethod51        this.balance += amount;52        System.out.println("Balance updated by: " + amount);53    }54    55    public void displayInfo() {56        System.out.println("Account: " + accountNumber);57        System.out.println("Owner: " + ownerName);58        System.out.println("Balance: $" + balance);59    }60}6162class SavingsAccount extends BankAccount {63    private double interestRate;64    65    public SavingsAccount(String ownerBob, double initialBalance5000.0, double rate0.03) {66        super(owner, initialBalance);67        this.interestRate→ 0.03 = rate0.03;68    }
  8. interest ← 150.0

    70public void addInterest() {71    // Can access protected field 'balance'  //?accessprotected72    double interest→ 150.0 = balance5000.0 * interestRate0.03;73    74    // Can call protected method  //?callprotected75    updateBalance(interest150.0);
  9. this.balance ← 5150.0

    50protected void updateBalance(double amount150.0) {  //?protectedmethod51    this.balance→ 5150.0 += amount150.0;52    System.out.println("Balance updated by: " + amount150.0);53}
    outputBalance updated by: 150.0
  10. updateBalance(interest);

    14        savings.displayInfo();15        savings.addInterest();  //?addinterest16        savings.displayInfo();17        18        System.out.println("\n=== Access Levels Demo ===");19        20        System.out.println("""21        Access Modifiers in Inheritance:22        23        | Modifier   | Same Class | Subclass | Other Classes |24        |------------|------------|----------|---------------|25        | private    | Yes        | No       | No            |26        | (default)  | Yes        | Yes*     | Yes*          |27        | protected  | Yes        | Yes      | No            |28        | public     | Yes        | Yes      | Yes           |29        30        * Same package only31        """);32    }33}3435class BankAccount {36    private String accountNumber;  //?privatefield37    protected String ownerName;    //?protectedfield38    protected double balance;      //?protectedbalance39    40    public BankAccount(String owner, double initialBalance) {41        this.accountNumber = generateAccountNumber();42        this.ownerName = owner;43        this.balance = initialBalance;44    }45    46    private String generateAccountNumber() {  //?privatemethod47        return "ACC" + System.currentTimeMillis() % 10000;48    }49    50    protected void updateBalance(double amount) {  //?protectedmethod51        this.balance += amount;52        System.out.println("Balance updated by: " + amount);53    }54    55    public void displayInfo() {56        System.out.println("Account: " + accountNumber);57        System.out.println("Owner: " + ownerName);58        System.out.println("Balance: $" + balance);59    }60}6162class SavingsAccount extends BankAccount {63    private double interestRate;64    65    public SavingsAccount(String owner, double initialBalance, double rate) {66        super(owner, initialBalance);67        this.interestRate = rate;68    }69    70    public void addInterest() {71        // Can access protected field 'balance'  //?accessprotected72        double interest = balance * interestRate;73        74        // Can call protected method  //?callprotected75        updateBalance(interest150.0);76        77        // Can access protected field 'ownerName'78        System.out.println("Interest added for " + ownerNameBob);
    outputInterest added for Bob

protected is visible in subclasses and same package. More open than private.

protected Access modifier: visible to subclasses and same package.

Multi-level inheritance

Chain of inheritance: grandparent → parent → child.

InheritanceChain.java
Replay: real traced execution (multi-file project)
// Multi-Level Inheritance Chain

public class InheritanceChain {
    public static void main(String[] args) {
        System.out.println("=== Multi-Level Inheritance ===\n");

        // Create SportsCar (3 levels deep)
        SportsCar ferrari = new SportsCar("Ferrari", "488", 2023, 660);
        ferrari.displayInfo();

        System.out.println("\n--- Demonstrating Methods ---");
        ferrari.start();      // From Vehicle
        ferrari.accelerate(); // From Car
        ferrari.boost();      // From SportsCar
        ferrari.stop();       // From Vehicle

        System.out.println("\n=== Inheritance Hierarchy ===");
        System.out.println("""

        Vehicle (grandparent)
           ↓
        Car (parent)
           ↓
        SportsCar (child)

        SportsCar inherits from Car,
        which inherits from Vehicle.

        SportsCar has access to ALL
        non-private members of both!
        """);

        System.out.println("=== Creating Different Levels ===\n");

        Vehicle vehicle = new Vehicle("Generic");
        vehicle.displayInfo();
        vehicle.start();

        System.out.println();

        Car car = new Car("Toyota", "Camry", 2022);
        car.displayInfo();
        car.start();
        car.accelerate();
    }
}

// Level 1: Base class
class Vehicle {
    protected String brand;

    Vehicle(String brand) {
        this.brand = brand;
    }

    void start() {
        System.out.println(brand + ": Starting engine...");
    }

    void stop() {
        System.out.println(brand + ": Stopping...");
    }

    void displayInfo() {
        System.out.println("Brand: " + brand);
    }
}

// Level 2: Extends Vehicle
class Car extends Vehicle {
    protected String model;
    protected int year;

    Car(String brand, String model, int year) {
        super(brand);
        this.model = model;
        this.year = year;
    }

    void accelerate() {
        System.out.println(brand + " " + model + ": Accelerating...");
    }

    @Override
    void displayInfo() {
        super.displayInfo();
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }
}

// Level 3: Extends Car
class SportsCar extends Car {
    private int horsepower;

    SportsCar(String brand, String model, int year, int hp) {
        super(brand, model, year);
        this.horsepower = hp;
    }

    void boost() {
        System.out.println(brand + " " + model + ": BOOST! (+" + horsepower + " HP)");
    }

    @Override
    void displayInfo() {
        super.displayInfo();  // Calls Car's displayInfo
        System.out.println("Horsepower: " + horsepower);
    }
}

  1. public static void main(String[] args)

    3public class InheritanceChain {4    public static void main(String[] args) {5        System.out.println("=== Multi-Level Inheritance ===\n");6        7        // Create SportsCar (3 levels deep)  //?createsports8        SportsCar ferrari = new SportsCar("Ferrari", "488", 2023, 660);9        ferrari.displayInfo();
    output=== Multi-Level Inheritance ===
  2. this.brand ← Ferrari

    pass 1 of 3
    52Vehicle(String brandFerrari) {53    this.brand→ Ferrari = brandFerrari;54}
    All 3 passes — pass 1 is the card above
    passbrandmodelyearhpthis.brandthis.modelthis.yearthis.horsepowerferrarivehiclecar
    1Ferrari4882023660Ferrari4882023660⟨SportsCar A⟩
    2GenericGeneric⟨Vehicle B⟩
    3ToyotaCamry2022ToyotaCamry2022⟨Car C⟩
  3. this.model ← 488, this.year ← 2023

    pass 1 of 2
    74Car(String brandFerrari, String model488, int year2023) {75    super(brand);  //?superlevel276    this.model→ 488 = model488;77    this.year→ 2023 = year2023;78}
  4. this.horsepower ← 660, ferrari ← ⟨SportsCar A⟩

    7        // Create SportsCar (3 levels deep)  //?createsports8        SportsCar ferrari→ ⟨SportsCar A⟩ = new SportsCar("Ferrari", "488", 2023, 660);9        ferrari.displayInfo();10        11        System.out.println("\n--- Demonstrating Methods ---");12        ferrari.start();      // From Vehicle13        ferrari.accelerate(); // From Car14        ferrari.boost();      // From SportsCar  //?boostcall15        ferrari.stop();       // From Vehicle16        17        System.out.println("\n=== Inheritance Hierarchy ===");18        System.out.println("""19        20        Vehicle (grandparent)2122        Car (parent)2324        SportsCar (child)25        26        SportsCar inherits from Car,27        which inherits from Vehicle.28        29        SportsCar has access to ALL30        non-private members of both!31        """);32        33        System.out.println("=== Creating Different Levels ===\n");34        35        Vehicle vehicle = new Vehicle("Generic");  //?createvehicle36        vehicle.displayInfo();37        vehicle.start();38        39        System.out.println();40        41        Car car = new Car("Toyota", "Camry", 2022);  //?createcar42        car.displayInfo();43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brand + ": Starting engine...");58    }59    60    void stop() {61        System.out.println(brand + ": Stopping...");62    }63    64    void displayInfo() {65        System.out.println("Brand: " + brand);66    }67}6869// Level 2: Extends Vehicle  //?level270class Car extends Vehicle {71    protected String model;72    protected int year;73    74    Car(String brand, String model, int year) {75        super(brand);  //?superlevel276        this.model = model;77        this.year = year;78    }79    80    void accelerate() {81        System.out.println(brand + " " + model + ": Accelerating...");82    }83    84    @Override85    void displayInfo() {86        super.displayInfo();  //?superdisplay87        System.out.println("Model: " + model);88        System.out.println("Year: " + year);89    }90}9192// Level 3: Extends Car  //?level393class SportsCar extends Car {94    private int horsepower;95    96    SportsCar(String brandFerrari, String model488, int year2023, int hp660) {97        super(brand, model, year);  //?superlevel398        this.horsepower→ 660 = hp660;99    }
  5. void displayInfo()

    pass 1 of 3
    64void displayInfo() {65    System.out.println("Brand: " + brandFerrari);66}
    outputBrand: Ferrari
    All 3 passes — pass 1 is the card above
    passbrandmodelyearthis.modelthis.yearcar
    1Ferrari
    2GenericCamry2022Camry2022⟨Car C⟩
    3Toyota
  6. System.out.println("Model: " + model);

    85void displayInfo() {86    super.displayInfo();  //?superdisplay87    System.out.println("Model: " + model488);88    System.out.println("Year: " + year2023);89}
    outputModel: 488
    Year: 2023
  7. System.out.println("Horsepower: " + horsepower);

    8        SportsCar ferrari = new SportsCar("Ferrari", "488", 2023, 660);9        ferrari.displayInfo();10        11        System.out.println("\n--- Demonstrating Methods ---");12        ferrari.start();      // From Vehicle13        ferrari.accelerate(); // From Car14        ferrari.boost();      // From SportsCar  //?boostcall15        ferrari.stop();       // From Vehicle16        17        System.out.println("\n=== Inheritance Hierarchy ===");18        System.out.println("""19        20        Vehicle (grandparent)2122        Car (parent)2324        SportsCar (child)25        26        SportsCar inherits from Car,27        which inherits from Vehicle.28        29        SportsCar has access to ALL30        non-private members of both!31        """);32        33        System.out.println("=== Creating Different Levels ===\n");34        35        Vehicle vehicle = new Vehicle("Generic");  //?createvehicle36        vehicle.displayInfo();37        vehicle.start();38        39        System.out.println();40        41        Car car = new Car("Toyota", "Camry", 2022);  //?createcar42        car.displayInfo();43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brand + ": Starting engine...");58    }59    60    void stop() {61        System.out.println(brand + ": Stopping...");62    }63    64    void displayInfo() {65        System.out.println("Brand: " + brand);66    }67}6869// Level 2: Extends Vehicle  //?level270class Car extends Vehicle {71    protected String model;72    protected int year;73    74    Car(String brand, String model, int year) {75        super(brand);  //?superlevel276        this.model = model;77        this.year = year;78    }79    80    void accelerate() {81        System.out.println(brand + " " + model + ": Accelerating...");82    }83    84    @Override85    void displayInfo() {86        super.displayInfo();  //?superdisplay87        System.out.println("Model: " + model);88        System.out.println("Year: " + year);89    }90}9192// Level 3: Extends Car  //?level393class SportsCar extends Car {94    private int horsepower;95    96    SportsCar(String brand, String model, int year, int hp) {97        super(brand, model, year);  //?superlevel398        this.horsepower = hp;99    }100    101    void boost() {  //?boostmethod102        System.out.println(brand + " " + model + ": BOOST! (+" + horsepower + " HP)");103    }104    105    @Override106    void displayInfo() {107        super.displayInfo();  // Calls Car's displayInfo  //?superchain108        System.out.println("Horsepower: " + horsepower660);109    }
    outputHorsepower: 660
    
    --- Demonstrating Methods ---
  8. void start()

    pass 1 of 3
    11        System.out.println("\n--- Demonstrating Methods ---");12        ferrari.start();      // From Vehicle13        ferrari.accelerate(); // From Car14        ferrari.boost();      // From SportsCar  //?boostcall15        ferrari.stop();       // From Vehicle16        17        System.out.println("\n=== Inheritance Hierarchy ===");18        System.out.println("""19        20        Vehicle (grandparent)2122        Car (parent)2324        SportsCar (child)25        26        SportsCar inherits from Car,27        which inherits from Vehicle.28        29        SportsCar has access to ALL30        non-private members of both!31        """);32        33        System.out.println("=== Creating Different Levels ===\n");34        35        Vehicle vehicle = new Vehicle("Generic");  //?createvehicle36        vehicle.displayInfo();37        vehicle.start();38        39        System.out.println();40        41        Car car = new Car("Toyota", "Camry", 2022);  //?createcar42        car.displayInfo();43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brandFerrari + ": Starting engine...");58    }
    outputFerrari: Starting engine...
    All 3 passes — pass 1 is the card above
    passbrandmodelhorsepoweryearthis.modelthis.yearcar
    1Ferrari488660
    2GenericCamry2022Camry2022⟨Car C⟩
    3ToyotaCamry
  9. void accelerate()

    pass 1 of 2
    12        ferrari.start();      // From Vehicle13        ferrari.accelerate(); // From Car14        ferrari.boost();      // From SportsCar  //?boostcall15        ferrari.stop();       // From Vehicle16        17        System.out.println("\n=== Inheritance Hierarchy ===");18        System.out.println("""19        20        Vehicle (grandparent)2122        Car (parent)2324        SportsCar (child)25        26        SportsCar inherits from Car,27        which inherits from Vehicle.28        29        SportsCar has access to ALL30        non-private members of both!31        """);32        33        System.out.println("=== Creating Different Levels ===\n");34        35        Vehicle vehicle = new Vehicle("Generic");  //?createvehicle36        vehicle.displayInfo();37        vehicle.start();38        39        System.out.println();40        41        Car car = new Car("Toyota", "Camry", 2022);  //?createcar42        car.displayInfo();43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brand + ": Starting engine...");58    }59    60    void stop() {61        System.out.println(brand + ": Stopping...");62    }63    64    void displayInfo() {65        System.out.println("Brand: " + brand);66    }67}6869// Level 2: Extends Vehicle  //?level270class Car extends Vehicle {71    protected String model;72    protected int year;73    74    Car(String brand, String model, int year) {75        super(brand);  //?superlevel276        this.model = model;77        this.year = year;78    }79    80    void accelerate() {81        System.out.println(brandFerrari + " " + model488 + ": Accelerating...");82    }
    outputFerrari 488: Accelerating...
  10. void boost()

    13        ferrari.accelerate(); // From Car14        ferrari.boost();      // From SportsCar  //?boostcall15        ferrari.stop();       // From Vehicle16        17        System.out.println("\n=== Inheritance Hierarchy ===");18        System.out.println("""19        20        Vehicle (grandparent)2122        Car (parent)2324        SportsCar (child)25        26        SportsCar inherits from Car,27        which inherits from Vehicle.28        29        SportsCar has access to ALL30        non-private members of both!31        """);32        33        System.out.println("=== Creating Different Levels ===\n");34        35        Vehicle vehicle = new Vehicle("Generic");  //?createvehicle36        vehicle.displayInfo();37        vehicle.start();38        39        System.out.println();40        41        Car car = new Car("Toyota", "Camry", 2022);  //?createcar42        car.displayInfo();43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brand + ": Starting engine...");58    }59    60    void stop() {61        System.out.println(brand + ": Stopping...");62    }63    64    void displayInfo() {65        System.out.println("Brand: " + brand);66    }67}6869// Level 2: Extends Vehicle  //?level270class Car extends Vehicle {71    protected String model;72    protected int year;73    74    Car(String brand, String model, int year) {75        super(brand);  //?superlevel276        this.model = model;77        this.year = year;78    }79    80    void accelerate() {81        System.out.println(brand + " " + model + ": Accelerating...");82    }83    84    @Override85    void displayInfo() {86        super.displayInfo();  //?superdisplay87        System.out.println("Model: " + model);88        System.out.println("Year: " + year);89    }90}9192// Level 3: Extends Car  //?level393class SportsCar extends Car {94    private int horsepower;95    96    SportsCar(String brand, String model, int year, int hp) {97        super(brand, model, year);  //?superlevel398        this.horsepower = hp;99    }100    101    void boost() {  //?boostmethod102        System.out.println(brandFerrari + " " + model488 + ": BOOST! (+" + horsepower660 + " HP)");103    }
    outputFerrari 488: BOOST! (+660 HP)
  11. void stop()

    14        ferrari.boost();      // From SportsCar  //?boostcall15        ferrari.stop();       // From Vehicle16        17        System.out.println("\n=== Inheritance Hierarchy ===");18        System.out.println("""19        20        Vehicle (grandparent)2122        Car (parent)2324        SportsCar (child)25        26        SportsCar inherits from Car,27        which inherits from Vehicle.28        29        SportsCar has access to ALL30        non-private members of both!31        """);32        33        System.out.println("=== Creating Different Levels ===\n");34        35        Vehicle vehicle = new Vehicle("Generic");  //?createvehicle36        vehicle.displayInfo();37        vehicle.start();38        39        System.out.println();40        41        Car car = new Car("Toyota", "Camry", 2022);  //?createcar42        car.displayInfo();43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brand + ": Starting engine...");58    }59    60    void stop() {61        System.out.println(brandFerrari + ": Stopping...");62    }
    outputFerrari: Stopping...
    
    === Inheritance Hierarchy ===
    
    Vehicle (grandparent)
       ↓
    Car (parent)
       ↓
    SportsCar (child)
    
    SportsCar inherits from Car,
    which inherits from Vehicle.
    
    SportsCar has access to ALL
    non-private members of both!
    === Creating Different Levels ===
  12. this.model ← Camry, this.year ← 2022, car ← ⟨Car C⟩

    pass 2 of 2
    41        Car car→ ⟨Car C⟩ = new Car("Toyota", "Camry", 2022);  //?createcar42        car.displayInfo();43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brand + ": Starting engine...");58    }59    60    void stop() {61        System.out.println(brand + ": Stopping...");62    }63    64    void displayInfo() {65        System.out.println("Brand: " + brand);66    }67}6869// Level 2: Extends Vehicle  //?level270class Car extends Vehicle {71    protected String model;72    protected int year;73    74    Car(String brandToyota, String modelCamry, int year2022) {75        super(brand);  //?superlevel276        this.model→ Camry = modelCamry;77        this.year→ 2022 = year2022;78    }
  13. System.out.println("Model: " + model);

    41        Car car = new Car("Toyota", "Camry", 2022);  //?createcar42        car.displayInfo();43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brand + ": Starting engine...");58    }59    60    void stop() {61        System.out.println(brand + ": Stopping...");62    }63    64    void displayInfo() {65        System.out.println("Brand: " + brand);66    }67}6869// Level 2: Extends Vehicle  //?level270class Car extends Vehicle {71    protected String model;72    protected int year;73    74    Car(String brand, String model, int year) {75        super(brand);  //?superlevel276        this.model = model;77        this.year = year;78    }79    80    void accelerate() {81        System.out.println(brand + " " + model + ": Accelerating...");82    }83    84    @Override85    void displayInfo() {86        super.displayInfo();  //?superdisplay87        System.out.println("Model: " + modelCamry);88        System.out.println("Year: " + year2022);89    }
    outputModel: Camry
    Year: 2022
  14. void accelerate()

    pass 2 of 2
    43        car.start();44        car.accelerate();45    }46}4748// Level 1: Base class  //?level149class Vehicle {50    protected String brand;51    52    Vehicle(String brand) {53        this.brand = brand;54    }55    56    void start() {57        System.out.println(brand + ": Starting engine...");58    }59    60    void stop() {61        System.out.println(brand + ": Stopping...");62    }63    64    void displayInfo() {65        System.out.println("Brand: " + brand);66    }67}6869// Level 2: Extends Vehicle  //?level270class Car extends Vehicle {71    protected String model;72    protected int year;73    74    Car(String brand, String model, int year) {75        super(brand);  //?superlevel276        this.model = model;77        this.year = year;78    }79    80    void accelerate() {81        System.out.println(brandToyota + " " + modelCamry + ": Accelerating...");82    }
    outputToyota Camry: Accelerating...

Child inherits from parent, which inherits from grandparent. Chain can be long.

Exercise: Practical.java

Build a complete class hierarchy with inheritance