Interview question
What is Abstraction in Java? Abstract Classes and Interfaces. Java में Abstraction क्या है? Abstract Classes और Interfaces क्या हैं?
Answer
Abstraction is a process of hiding complex implementation details and showing only the essential features. It's achieved through abstract classes and interfaces.
// Abstract Class
public abstract class Shape {
// Abstract method (no implementation)
public abstract double calculateArea();
public abstract double calculatePerimeter();
// Concrete method
public void displayInfo() {
System.out.println('This is a shape');
}
}
// Concrete implementations
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
public class Rectangle extends Shape {
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
}
// Interface
public interface Drawable {
void draw(); // Implicitly abstract
void erase();
}
public class Drawing implements Drawable {
@Override
public void draw() {
System.out.println('Drawing...');
}
@Override
public void erase() {
System.out.println('Erasing...');
}
}
// Usage
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rect = new Rectangle(4, 6);
System.out.println('Circle Area: ' + circle.calculateArea());
System.out.println('Rectangle Area: ' + rect.calculateArea());
}
}
// Abstract Class vs Interface:
// Abstract Class: Can have state (variables), constructors, private methods
// Interface: Only behavior contract, no state (until Java 8, default methods)
// Abstract Class: 'is-a' relationship
// Interface: 'can-do' capabilityAbstraction: Complex details को hide करना।
Abstract Class:
- public abstract class Shape {}
- Abstract methods के साथ
- State रख सकता है
- Constructor हो सकता है
Interface:
- public interface Drawable {}
- Method contracts define करता है
- State नहीं (Java 8+ से default methods)
- Multiple inheritance support करता हैWas this answer clear?