Abstraction

Abstraction refers to the hiding of complex details and showing only necessary information. For example, when you turn your lights on, the room lights up. You just turn the light on. You do not need to know how did the electrons flow? What is going on in the wiring?

Abstraction can be achieved with the help of:

  1. Abstract Classes
  2. Interfaces

Abstraction with Abstract Class

Abstract class is declared with abstract keyword. We will create an abstract class called Shape with an abstract method calculateArea(). We'll also create two concrete subclasses, Circle and Rectangle, that inherit from the Shape class and provide their own implementations of the calculateArea() method.

Abstraction with Interfaces

In this example, we'll use an interface called Sound to define a contract specifying a makeSound() method. We'll create two classes, Dog and Cat, that implement the Sound interface and provide their own makeSound() implementations.

Benefits of Abstraction

  • Code Reusability: Abstraction promotes code reusability by allowing multiple classes to implement the same interface or inherit from the same abstract class.
  • Modularity: It helps in breaking down complex systems into manageable and modular components.
  • Encapsulation: Abstraction supports encapsulation by hiding implementation details and exposing a well-defined interface.
  • Maintainability: It enhances code maintainability by making it easier to modify or extend the system without affecting other parts of the code.

Abstraction is a fundamental concept in Java that helps to write organized and structured code for designing classes and interfaces. It enables the creation of clean and understandable code, making it easier to work with complex systems.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min