Middle
Millised polümorfismi rakendamise mehhanismid Java-s eksisteerivad?
sobes.tech AI
Vastus AI-lt
-
** Compile-time polymorphism (static polymorphism)**: Implemented through method overloading. Methods have the same name but different signatures (number, type, or order of arguments).
class Calculator { // Overloading the add method public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } } -
** Runtime polymorphism (dynamic polymorphism)**: Implemented through method overriding. A method in a subclass has the same signature as in the parent class and provides its own implementation. The decision of which method to call is made at runtime based on the actual object type.
class Animal { public void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { // Override the sound method @Override public void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { // Override the sound method @Override public void sound() { System.out.println("Cat meows"); } }