Abstraction

Abstraction is one of the four fundamental Object-Oriented Programming (OOP) concepts in Java, alongside Encapsulation, Inheritance, and Polymorphism. It helps developers focus on what an object does rather than how it does it.

Abstraction is the process of hiding the implementation details of a class while exposing only the necessary functionality. This allows developers to work with high-level concepts rather than getting lost in the details of implementation. For example, when you use a mobile phone, you interact with its features like calling and texting without knowing the internal circuitry and how everything works inside. That’s abstraction!

In Java, abstraction is achieved using:

  • Abstract Classes
  • Interfaces

Abstract Classes

An abstract class in Java is a class that cannot be instantiated (you cannot create objects from it). It serves as a blueprint for other classes. It can have both abstract methods (methods without a body) and concrete methods (methods with a body).

Example:

Interfaces

An interface in Java is a completely abstract class that only contains method declarations (without implementations). A class that implements an interface must provide implementations for all its methods.

Example:

Benefits of Abstraction

  • Reduces Complexity: Developers can focus on high-level design rather than getting lost in implementation details.
  • Enhances Code Maintainability: Changes in the internal implementation do not affect other parts of the code.
  • Improves Code Reusability: Abstract classes and interfaces allow code to be reused efficiently.

Abstract Class vs Interface

Feature Abstract Class Interface
Methods Can have abstract and concrete methods Only abstract methods (until Java 8, which introduced default methods)
Multiple Inheritance Not supported (A class can extend only one abstract class) Supported (A class can implement multiple interfaces)
Variables Can have instance variables Only constants (public, static, and final by default)
Constructors Can have constructors Cannot have constructors