Java Intermediate Day 2: Inheritance & Polymorphism

Goal of this Day

Today you will learn:

By the end, you will be able to create class hierarchies and use polymorphism effectively.

Step 1: The extends Keyword

Use extends to create a subclass from a base class.


class Animal {
    void makeSound() {
        System.out.println("Animal sound");
    }
}

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

Explanation:

Step 2: Method Overriding

A subclass can provide its own implementation of a method.


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

Explanation:

Step 3: The super Keyword

super refers to the parent class and can be used to call parent methods or constructors.


class Dog extends Animal {
    void makeSound() {
        super.makeSound(); // calls Animal's makeSound
        System.out.println("Woof");
    }
}

Step 4: Runtime Polymorphism

Polymorphism allows a parent reference to point to a child object.


Animal myAnimal = new Dog();
myAnimal.makeSound(); // Prints "Woof"

Explanation:

Practice


class Animal {
    void makeSound() {
        System.out.println("Animal sound");
    }
}

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

Exercise

Create a base class Shape and subclasses Circle and Rectangle with overridden methods.

Steps:

Example:


class Shape {
    void draw() {
        System.out.println("Drawing a shape");
    }
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing a circle");
    }
}

class Rectangle extends Shape {
    void draw() {
        System.out.println("Drawing a rectangle");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape1 = new Circle();
        Shape shape2 = new Rectangle();

        shape1.draw(); // Drawing a circle
        shape2.draw(); // Drawing a rectangle
    }
}