Abstraction in Java — Java Technical Interview Questions & Answers
Abstraction in Java
Abstraction in Java
- Abstraction: show what, hide how. abstract class + abstract method = must implement in child.
- You cannot write new Shape() if Shape is abstract.
- Interface is also abstraction (can-do contract).
- Write one tiny example for Abstraction. Compile, print one result, and say the output out loud before you type.
- Use Abstraction only when the problem needs it. Don’t force it into every program. Know one beginner trap.
- Let's take this on the board with one tiny Main class — no extra files. Abstraction in Java — output: 12.56. Shape has no body for area(); Circle supplies it. new Shape() would not compile. Start from main, go line by line, and stop at each print. That output is the proof for Abstraction.
Technical Interview Tip: Say: new Shape() fails; new Circle(2).area() works.
Code Examples for Abstraction in Java
Example
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return 3.14 * r * r; }
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(2);
System.out.println(s.area());
}
}Abstraction in Java — output: 12.56. Shape has no body for area(); Circle supplies it. new Shape() would not compile.
How to Explain Abstraction in Java to an Interviewer
What is Abstraction?
Abstraction is a Java idea you should explain with one small example. Know the keyword / API used for Abstraction. Type a tiny Main and print one result. For Abstraction, say the output before you code.
Why do we use Abstraction in Java?
Makes the program clearer or safer Abstraction is a Java idea you should explain with one small example.
Write one small example of Abstraction.
Show syntax Say what prints
What mistake do beginners make with Abstraction?
Only the name, no example Abstraction — only memorising the heading. No example, no trap.
Where is Abstraction used in a real program?
Day-to-day Java code