How do you achieve abstraction in Java?
Use abstract classes (partial implementations with abstract methods) or interfaces (pure contracts). Callers depend on the abstract type and never see the concrete class behind it.
Explain it simply
When you book on IRCTC you choose "pay", not "talk to this particular bank over this protocol". The app presents one idea, payment, and hides the many ways it happens.
In Java you declare the idea as an interface or abstract class, write concrete classes for each way, and let calling code hold only the abstract type.
Example
abstract class Shape {
abstract double area(); // no body
void describe() { System.out.println("Area = " + area()); }
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
class Rect extends Shape {
double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
double area() { return w * h; }
}
Shape s = new Rect(4, 5);
s.describe(); // prints: Area = 20.0new Shape() is a compile error, because the idea is incomplete.
What to say in the interview
"I achieve abstraction with interfaces for pure contracts and abstract classes when I also want shared state or code. Client code programs to the abstract type, so implementations can change without breaking it."
Common mistakes
- Believing abstract classes give 100% abstraction while interfaces do not. Modern interfaces can have default methods too.