Java - OOP - Abstraction

Java Abstraction is a process of hiding implementation details and providing only the essential features of an object to the outside world. It is one of the four fundamental concepts of object-oriented programming (OOP), the other three being Encapsulation, Inheritance, and Polymorphism.

Abstraction is achieved in Java through abstract classes and interfaces. An abstract class is a class that cannot be instantiated, i.e., an object cannot be created from it. It can contain both abstract and concrete (non-abstract) methods, and it can also contain variables, constructors, and static methods. An abstract method is a method that is declared but not implemented in the abstract class. The implementation of the abstract method is left to the subclass that extends the abstract class.

An interface, on the other hand, is a collection of abstract methods and constants. An interface can be implemented by any class, and it specifies the behavior that a class should exhibit. All the methods declared in an interface are abstract by default, and the interface can also contain static methods and default methods (concrete methods with a default implementation).

Abstraction provides a way to define a common interface that multiple classes can implement, even if those classes have different implementations of the interface. It also helps to reduce code duplication and increase code reusability.

// Abstract class
abstract class Shape {
    String color;

    Shape(String color) {
        this.color = color;
    }
 
    // Abstract method
    abstract double area();
  
    // Concrete method
    void display() {
        System.out.println("Color: " + color);
    }
}

// Interface
interface Drawable {
    void draw();
}

// Concrete class implementing the abstract class and interface
class Rectangle extends Shape implements Drawable {
    double length, width;
    
    Rectangle(String color, double length, double width) {
        super(color);
        this.length = length;
        this.width = width;
    }
    
    double area() {
        return length * width;
    }
    
    public void draw() {
        System.out.println("Drawing Rectangle");
    }
}

public class AbstractionExample {
    public static void main(String[] args) {
        Rectangle r = new Rectangle("Red", 5, 4);
        r.display();
        System.out.println("Area: " + r.area());
        r.draw();
    }
}

In this example, the Shape class is an abstract class that contains an abstract method area() and a concrete method display(). The Drawable interface contains a single method draw(). The Rectangle class extends the Shape class and implements the Drawable interface. It provides the implementation for the area() method and the draw() method. The main() method creates an object of the Rectangle class and invokes the display(), area(), and draw() methods.