Sobes.tech
Junior

What is inheritance and polymorphism in reference data types?

sobes.tech AI

Answer from AI

Inheritance is a mechanism that allows a new class (subclass/child) to inherit properties (fields) and behaviors (methods) from an existing class (superclass/parent), extending or overriding functionality. This promotes code reuse and establishes "is-a" relationships.

Polymorphism is the ability of objects of different classes to respond to the same method name differently, depending on their specific type at runtime. It provides flexibility and extensibility of code, allowing objects of subclasses to be handled through a reference to the superclass.

In reference data types (classes), these concepts play a key role:

  • Inheritance: A subclass gains access to the members of the superclass and can add its own or modify the behavior of inherited methods (overriding). An object of a subclass can be used wherever a superclass object is expected.
  • Polymorphism: Different objects related to the same inheritance hierarchy can be processed by the same code, calling the same method, but the implementation of this method will be specific to the particular type of object at runtime.

Example in Java:

// Superclass (parent)
class Animal {
    public void makeSound() {
        System.out.println("Makes a sound");
    }
}

// Subclass (child), inherits from Animal
class Dog extends Animal {
    // Override method from superclass
    @Override
    public void makeSound() {
        System.out.println("Bark!");
    }
}

// Subclass (child), inherits from Animal
class Cat extends Animal {
    // Override method from superclass
    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}

// Example of polymorphism
public class PolymorphismExample {
    public static void main(String[] args) {
        Animal myAnimal = new Animal(); // superclass object
        Animal myDog = new Dog();       // subclass object, reference to superclass
        Animal myCat = new Cat();       // subclass object, reference to superclass

        myAnimal.makeSound(); // Outputs: Makes a sound
        myDog.makeSound();    // Outputs: Bark! (polymorphism - Dog's method is called)
        myCat.makeSound();    // Outputs: Meow! (polymorphism - Cat's method is called)
    }
}