Sobes.tech
Junior — Middle

Kuidas saab koodi kaudu objektide käitumist juhtida polümorfismi abil?

sobes.tech AI

Vastus AI-lt

Polymorphism in Java allows objects of different classes to respond differently to the same method calls, which is useful for managing object behavior.

To implement behavior management through polymorphism, a base interface or abstract class with a defined method is usually created, and then different derived classes implement this method in their own way.

Example:

interface Animal {
    void makeSound();
}

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

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

public class Main {
    public static void main(String[] args) {
        Animal[] animals = {new Dog(), new Cat()};
        for (Animal animal : animals) {
            animal.makeSound(); // Method call depends on the specific object
        }
    }
}

This way, object behavior management reduces to calling a single method, and the specific implementation is determined at runtime based on the object type. This facilitates code extension and maintenance.