Understanding Java Abstraction

Abstraction is a fundamental concept in Java that involves hiding the implementation details of an object and exposing only the essential features. In Java, abstraction is achieved through abstract classes and interfaces.

Abstract Class Example:


// Example of an abstract class
public abstract class Shape {
  // Abstract method (to be implemented by subclasses)
  public abstract double calculateArea();

  // Concrete method
  public void display() {
    System.out.println("This is a shape.");
  }
}

Concrete Subclass Example:


// Concrete subclass implementing the abstract class
public class Circle extends Shape {
  private double radius;

  // Constructor
  public Circle(double radius) {
    this.radius = radius;
  }

  // Implementation of the abstract method
  @Override
  public double calculateArea() {
    return Math.PI * radius * radius;
  }
}

Interface Example:


// Example of an interface
public interface Sound {
  // Abstract method (to be implemented by classes)
  void makeSound();
}

Class Implementing Interface Example:


// Class implementing the interface
public class Dog implements Sound {
  // Implementation of the interface method
  @Override
  public void makeSound() {
    System.out.println("Woof! Woof!");
  }
}

Using Abstraction:


// Using abstract class and concrete subclass
Shape circle = new Circle(5.0);
circle.display();
System.out.println("Area of circle: " + circle.calculateArea());

// Using interface and class implementing it
Sound dog = new Dog();
dog.makeSound();

Note:

Abstraction allows you to define the structure of a class or interface while leaving the implementation details to its subclasses or implementing classes. It helps in designing a more modular and flexible code structure.