Junior
What is the difference between abstraction and polymorphism?
sobes.tech AI
Answer from AI
Abstraction focuses on hiding implementation details and providing a simplified view of an object. Polymorphism allows handling objects of different classes as objects of a common base class or interface, performing specific actions for each object.
| Characteristic | Abstraction | Polymorphism |
|---|---|---|
| Essence | Hiding details, providing a general view | Ability to process objects of different types uniformly |
| Goal | Simplification, reducing complexity | Flexibility, extensibility, code universality |
| How achieved | Abstract classes, interfaces | Method overloading, method overriding, interfaces |
| Example | Car class without engine details |
drive() method in different classes (Sedan, Truck) |
Example of abstraction (using abstraction):
interface Shape {
// Abstract method
double calculateArea();
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
// Implementation details are hidden behind the interface method
return Math.PI * radius * radius;
}
}
Example of polymorphism:
// Using polymorphism
Shape myShape = new Circle(5);
// Calling calculateArea() through a reference of the base type (interface Shape)
// The calculateArea() method from the Circle class will actually be executed
double area = myShape.calculateArea();
System.out.println("Area: " + area);