What is abstraction in Java

Nikhil Soman Sahu
2 min readApr 18, 2023

--

Abstraction is a fundamental concept in object-oriented programming (OOP) that allows programmers to create complex systems by breaking them down into smaller, more manageable pieces. In Java, abstraction is achieved through the use of abstract classes and interfaces, which provide a way to define common behavior that can be shared by multiple classes.

At its core, abstraction is about creating a simplified view of an object or system that focuses on the most important aspects while hiding or abstracting away the implementation details. This allows developers to work at a higher level of abstraction, focusing on what an object or system does rather than how it does it.

Abstract classes in Java are classes that cannot be instantiated directly but can be extended by other classes. Abstract classes can contain both abstract and non-abstract methods, as well as instance variables and constants. Abstract methods are defined without an implementation and must be implemented by any non-abstract subclass that extends the abstract class.

For example, consider an abstract class called Shape that defines the basic properties and behaviors of all shapes:

public abstract class Shape {
protected int x;
protected int y;
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public abstract void draw();
public abstract double getArea();
}

In this example, Shape defines two instance variables to represent the position of the shape, as well as two abstract methods, draw() and getArea(). Any concrete subclass that extends Shape must provide an implementation for these two methods.

Interfaces, on the other hand, are similar to abstract classes in that they define a set of methods that must be implemented by any class that implements the interface. However, unlike abstract classes, interfaces cannot contain instance variables or non-abstract methods.

Here’s an example of an interface called Drawable that defines a single method, draw

public interface Drawable {
public void draw();
}

Any class that implements the Drawable interface must provide an implementation for the draw() method.

Abstraction is a powerful tool for creating reusable, maintainable code in Java. By abstracting away implementation details and focusing on behavior, developers can create flexible, extensible systems that are easier to modify and maintain over time.

--

--

Nikhil Soman Sahu
Nikhil Soman Sahu

Written by Nikhil Soman Sahu

Sr Software Developer | Spring Boot | Flutter | Dart | Java

No responses yet