Dezign Patterns
Abstraction
📦 Definition: Abstraction is the process of hiding the internal implementation details and showing only the essential features of an object or system to the outside world.
🎯 Intent : Abstraction hides the "how", so you can focus on the "what"
- Abstract class or Interface can't be instantiated
- Abstract class may have the constructor , but independently abstract object doesn't exist
- It needs to be instantiated with sub classes.
When a client uses this abstract class, they do not need to know how these methods are implemented.
They simply call the methods, trusting that the concrete subclass will provide the correct behavior as per the contract.
abstract class Shape {
String color;
public Shape(String color) {
this.color = color;
}
abstract double calculateArea(); // Abstract method: must be implemented by subclasses
void displayColor() {
System.out.println("Color: " + color); // Concrete method: shared by all shapes
}
}
class Circle extends Shape {
double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
double length;
double width;
public Rectangle(String color, double length, double width) {
super(color);
this.length = length;
this.width = width;
}
@Override
double calculateArea() {
return length * width;
}
}
// Driver code
Shape rectangle = new Rectangle("Blue", 4.0, 6.0);
rectangle.displayColor();
System.out.println("Rectangle Area: " + rectangle.calculateArea());