INSTACK 360

Java Inheritance & Polymorphism

Master code reusability with Inheritance and dynamic method dispatch using Polymorphism in Java.

Advanced 5 min read

Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

We use the extends keyword to perform inheritance in Java.

class Animal {
    public void eat() {
        System.out.println("I can eat");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("I can bark");
    }
}

Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

Method Overriding (Runtime Polymorphism)

When a subclass provides a specific implementation of a method that is already provided by its parent class, it is called Method Overriding.

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

class Pig extends Animal {
    @Override
    public void sound() {
        System.out.println("The pig says: wee wee");
    }
}