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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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