Polymorphism is one of the four pillars of object-oriented programming (OOP) and refers to the ability for objects from different classes to be treated as objects from the same base class. Polymorphism in Java is implemented through two main techniques: method overloading (methods with the same name in the same class, but with different parameters) and method overriding (methods with the same signature in different classes, where the subclass provides its implementation itself).
Overloading
Method overloading allows a class to have multiple methods with the same name but different parameters. The Java compiler chooses which method to call based on the method signature (type and number of parameters).
Example of method overloading:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
Overriding
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its base class (superclass). The method signature in the subclass must be identical to the signature in the superclass.
Method overriding example:
public class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog's bark");
}
}
Polymorphism example
public class PolymorphismExample {
public static void main(String[] args) {
Animal animal1 = new Animal();
Animal animal2 = new Dog();
animal1. makeSound(); // Output: Generic animal sound
animal2. makeSound(); // Output: Dog's bark
}
}
In this example, "animal2" is an instance of "Dog", but it is declared as an "Animal" type. When the "makeSom()" method is called, Java uses the specific implementation of the "Dog" class, showing how polymorphism allows different types of objects to be treated uniformly.
Polymorphism in Java is a powerful tool that promotes code reuse, flexibility, and extensibility in object-oriented systems.
Nenhum comentário:
Postar um comentário