Sobes.tech
Junior — Middle

Kuidas saab rakendada polümorfismi põhimõtteid erinevat tüüpi objektidega töötamisel?

sobes.tech AI

Vastus AI-lt

Polymorphism allows working with objects of different classes through a common interface or base class, calling methods that are implemented differently in each class. This simplifies the code and increases its flexibility.

Example:

interface Animal {
    void sound();
}

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

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

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound(); // Hau

        a = new Cat();
        a.sound(); // Miau
    }
}

Here, a variable of type Animal can refer to objects of different classes, and the call to the sound() method will be executed according to the actual type of the object.