22.09 Inheritance and Polymorphism

Inheritance and Polymorphism

Overview

Inheritance allows a class to inherit fields and methods from another class. Polymorphism enables methods to perform different tasks based on the object.

Topics

Examples

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

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks

Tags

#java #inheritance #polymorphism #overriding #oop #super