Abstraction
Abstraction is one of the four pillars of object-oriented programming (OOP). It is the process of hiding the implementation details from the user and only showing the essential functionality. This makes the code more modular and reusable, and it also makes it easier to understand and maintain. It allows you to define a blueprint for a class without providing a complete implementation.
In Java, abstraction can be achieved using abstract classes and interfaces.
1. Abstract Classes
With abstract classes in Java allows you to define a common interface (method signatures) for a group of related classes while leaving the implementation details to the concrete subclasses. Abstract classes serve as a blueprint for creating more specialized classes.
Use the abstract
keyword to declare an abstract class. An abstract class can have both abstract methods (without implementation) and concrete methods (with implementation).
This example demonstrates how abstraction with abstract classes allows you to define a common interface (area()
method) for related classes (Circle
and Rectangle
) while letting each subclass provide its own implementation of the method.
2. Interface
An interface is a special type of abstract class that only contains abstract methods. Interfaces cannot contain any fields or constructors. It is a collection of abstract methods (methods without a body) that define a contract for classes that implement the interface. When a class implements an interface, it is obligated to provide concrete (non-abstract) implementations for all the methods declared in that interface.
In the Main
class, we create instances of Circle
and Rectangle
, and then we call the area()
and perimeter()
methods on these instances to calculate and display the area and perimeter of the shapes.
By using an interface, we achieve abstraction, as we define a common contract (the Shape
interface) that multiple classes can adhere to while providing their own implementations for the methods. This allows for code flexibility and modularity in your Java programs.
Abstraction enables you to create well-organized and modular software systems by separating the interface from the implementation, allowing for flexibility and extensibility in your code.
Last updated