Lesson 22
Abstraction
Abstraction hides implementation details and shows only essential features. Achieved using abstract classes and interfaces.
Java Track
Save progress as you learn.
61 lessons
Lesson content
Abstraction shows only essential features, hiding implementation details. Reduces complexity and improves security.
Definition List
- Abstraction: Hiding implementation details, showing only essential functionality.
- Abstract Class: Declared with abstract keyword. Cannot be instantiated.
- Abstract Method: Method with no body. Must be implemented by subclasses.
- Implementation: Actual code defining how a method works.
Abstract Method Syntax
abstract void draw();Abstract Class Syntax
abstract class Shape {
abstract void draw();
}Rules of Abstract Classes
- Cannot be instantiated.
- Can contain abstract and non-abstract methods.
- Subclass must implement all abstract methods.
- Must have at least one abstract method.
Example 01: Abstract Class in Java
abstract class Shape {
abstract void draw();
void message() {
System.out.println("Message From Shape");
}
}
class rectangleShape extends Shape {
@Override
void draw() {
System.out.println("Draw Rectangle Using Length & Breadth..");
}
}
public class abstractDemo {
public static void main(String args[]) {
rectangleShape o = new rectangleShape();
o.draw();
o.message();
}
}Output
Draw Rectangle Using Length & Breadth..
Message From ShapeKey Points
- Abstract methods have no body.
- Must be declared inside abstract classes.
- Abstract classes cannot be instantiated.
- Subclasses must implement abstract methods.
- Abstraction works via abstract classes and interfaces.
FAQ
1. What is abstraction in Java?
Hiding implementation details and showing only essential functionality.
2. Can we instantiate an abstract class?
No. Create objects using the subclass instead.
3. Abstract method vs normal method?
Abstract has no body. Normal method has full implementation.
Where Java is used
Java in real-world development
Abstract Class
Declared with abstract keyword. Cannot be instantiated. Can have both abstract and concrete methods.
Abstract Method
No body. Must be implemented by subclasses. Declared inside abstract classes only.
Subclass Requirement
Subclass must implement all abstract methods or be declared abstract itself.
Object Creation
Cannot create objects from abstract class. Use the concrete subclass instead.
Real-World Example
Car driver uses pedals without knowing engine internals. That's abstraction.
Abstraction vs Encapsulation
Abstraction hides design complexity. Encapsulation hides data using access modifiers.