Sobes.tech
Middle

What are inheritance and polymorphism in reference data types?

sobes.tech AI

Answer from AI

Inheritance is a mechanism that allows a new class (subclass, child class) to inherit fields and methods from an existing class (parent class, superclass). This promotes code reuse and class hierarchy.

Polymorphism (many forms) is the ability of an object to take on multiple forms. In the context of reference data types, it means that a superclass variable can refer to a subclass object. This allows handling objects of different subclasses in a unified way through a common interface or superclass.

There are two main types of polymorphism:

  1. Compile-time (static polymorphism): Usually achieved through method overloading, where multiple methods in a class have the same name but different signatures (number and/or types of parameters).
  2. Runtime (dynamic polymorphism): Achieved through method overriding, where a subclass provides its own implementation of a method already defined in the superclass. When such a method is called through a superclass reference, the subclass's implementation is executed (if the object type is a subclass).

Example of inheritance and dynamic polymorphism:

// Base class
class Animal {
    public void makeSound() {
        System.out.println("Generic animal sound");
    }
}

// Subclass
class Dog extends Animal {
    @Override // Method overriding
    public void makeSound() {
        System.out.println("Woof!");
    }
}

// Subclass
class Cat extends Animal {
    @Override // Method overriding
    public void makeSound() {
        System.out.println("Meow!");
    }
}

public class Main {
    public static void main(String[] args) {
        // Static type of variable Animal, dynamic type of object Dog
        Animal myDog = new Dog();
        // Static type of variable Animal, dynamic type of object Cat
        Animal myCat = new Cat();
        // Static type of variable Animal, dynamic type of object Animal
        Animal genericAnimal = new Animal();

        // Demonstration of polymorphism
        myDog.makeSound(); // Calls method from Dog
        myCat.makeSound(); // Calls method from Cat
        genericAnimal.makeSound(); // Calls method from Animal
    }
}

In this example, Dog and Cat inherit from Animal. The variables myDog, myCat, and genericAnimal have static type Animal, but refer to objects of different dynamic types (Dog, Cat, Animal). When calling the makeSound() method, each reference executes the corresponding method implementation depending on the dynamic type of the object, which is runtime polymorphism.

What are inheritance and polymorphism in reference… - sobes.tech