Abstraction
TL;DR
- Abstraction is the process of hiding complex implementation details and showing only the essential features to the user.
- It reduces code complexity and allows developers to focus on what an object does rather than how it does it.
- In Java, Abstraction is achieved using Abstract Classes (partial abstraction) and Interfaces (100% abstraction, historically).
Concept
Think of driving a car. You know that pressing the accelerator pedal makes the car go faster. You interact with the abstraction (the pedal). You do not need to understand fuel injection, pistons, or the transmission system (the implementation details) to drive.
If those internal systems change (e.g., upgrading to an electric engine), your interface (the pedal) remains exactly the same. This is the power of abstraction in software design.
Examples
// The Abstraction
abstract class DatabaseConnection {
// Abstract method: defines WHAT to do, but not HOW.
public abstract void connect();
// Concrete method: shared logic
public void logConnection() {
System.out.println("Connection logged to audit file.");
}
}
// The Implementation
class PostgresConnection extends DatabaseConnection {
@Override
public void connect() {
System.out.println("Connecting to PostgreSQL using port 5432 and TCP/IP...");
}
}
public class AbstractionExample {
public static void main(String[] args) {
// You cannot instantiate an abstract class:
// DatabaseConnection db = new DatabaseConnection(); // Error!
// You use the abstraction reference to point to the implementation
DatabaseConnection db = new PostgresConnection();
db.connect();
db.logConnection();
}
}
Interview Questions
Q: Why do we need Abstraction?
A: Abstraction allows for loose coupling. By depending on abstractions (like Interfaces) instead of concrete classes, you can swap out the underlying implementations without breaking the rest of your application. It also hides sensitive or incredibly complex logic from the API surface.
Q: Can an abstract class have a constructor?
A: Yes. Even though you cannot instantiate an abstract class using new, it can have constructors. These constructors are called when a concrete subclass is instantiated (via super()), which is useful for initializing common fields defined in the abstract class.