Abstraction
What is Abstraction?
Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it. In Java programming, abstraction is achieved using Abstract classes and interfaces.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
Abstract Classes in Java:
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Definition and Declaration:
abstract class A{}
public abstract class Shape {
// Abstract method declaration
public abstract double calculateArea();
// Concrete method
public void display() {
System.out.println("This is a shape.");
}
}
Subclassing and Implementation
Concrete subclasses must provide implementations for all abstract methods defined in the abstract class.
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Interface
What is an Interface?
Java interface is a collection of abstract methods. The interface is used to achieve abstraction in which you can define methods without their implementations (without having the body of the methods). An interface is a reference type and is similar to the class.
public interface Printable {
void print();
}
Declaring an Interface in Java
The interface keyword is used to declare an interface.
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations\
}
Abstraction V/S Interface
Abstraction in Real-World Examples
Database Connectivity
Consider an abstract database connection class that defines the essential methods for connecting, querying, and closing connections. Concrete classes for specific databases (e.g., MySQL, PostgreSQL) implement these methods with their database-specific details.
GUI Frameworks
In graphical user interface (GUI) frameworks, an abstract class or interface may define methods for rendering components, handling events, and managing user input. Concrete classes, such as buttons or panels, implement these methods to provide specific behaviors.
Inference
Abstraction is a powerful tool in Java that enables developers to design and build scalable, maintainable, and adaptable systems. By focusing on essential features and hiding implementation details, abstraction fosters code reuse, flexibility, and simplicity. Whether through abstract classes or interfaces, the use of abstraction is integral to creating robust and efficient object-oriented applications. As you continue your journey in Java development, leverage abstraction to design elegant and modular solutions that stand the test of time.
Comments