Can you explain the difference between polymorphism and abstraction in object-oriented programming?
sobes.tech AI
Answer from AI
Polymorphism and abstraction are two key principles of object-oriented programming, but they solve different problems.
-
Abstraction is the process of highlighting essential characteristics of an object while hiding implementation details. Abstraction allows describing an interface or behavior without specifics. For example, an abstract class or interface defines a set of methods that must be implemented in subclasses.
-
Polymorphism is the ability of objects of different classes to respond to the same messages (method calls) in different ways. Thanks to polymorphism, the same interface can be used to work with different types of objects.
Example:
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.makeSound(); // Bark
a = new Cat();
a.makeSound(); // Meow
}
}
Here, the Animal interface is an example of abstraction, and calling makeSound() on different objects is an example of polymorphism.