topicuncategorized

Subtype Polymorphism

Subtype polymorphism (or inclusion polymorphism) refers to the ability to use a derived class in place of its base class. This is achieved through inheritance and interface implementation.

Examples

Java

public interface Animal {
    void makeSound();
}

public class Dog implements Animal {
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class Cat implements Animal {
    public void makeSound() {
        System.out.println("Meow");
    }
}

public class Solution {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Animal cat = new Cat();
        dog.makeSound();  // Output: Bark
        cat.makeSound();  // Output: Meow
    }
}

Python

class Animal:
    def make_sound(self):
        raise NotImplementedError

class Dog(Animal):
    def make_sound(self):
        print("Bark")

class Cat(Animal):
    def make_sound(self):
        print("Meow")

# Example usage
dog = Dog()
cat = Cat()
dog.make_sound()  # Output: Bark
cat.make_sound()  # Output: Meow