1. Introduction to Abstraction
1.1 What is Abstraction
Abstraction means hiding internal details and showing only essential functionality to the user.
1.2 Why Use Abstraction
- Reduces complexity
- Improves code readability
- Enhances security
1.3 Real-World Example
ATM machine:
- User → withdraw money
- Hidden → internal processing
1.4 Abstraction vs Encapsulation
- Abstraction → hides implementation
- Encapsulation → hides data
1.5 Ways to Achieve Abstraction
- Abstract classes
- Interfaces
2. Abstract Classes
2.1 Definition
An abstract class is a class that cannot be instantiated and may contain abstract methods.
2.2 Syntax
abstract class Vehicle {
abstract void start();
}
2.3 Features
- Can have abstract and non-abstract methods
- Can have constructors
- Cannot create objects directly
2.4 Example
abstract class Animal {
abstract void sound(); void sleep() {
System.out.println("Sleeping");
}
}
2.5 When to Use
- When classes share common behavior
- When partial abstraction is needed
3. Abstract Methods
3.1 Definition
A method declared without implementation.
3.2 Syntax
abstract void display();
3.3 Rules
- Must be inside abstract class
- Must be implemented in subclass
3.4 Example
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
4. Interfaces
4.1 Definition
An interface is a blueprint of a class that contains abstract methods.
4.2 Syntax
interface Animal {
void sound();
}
4.3 Features
- All methods are abstract by default (basic concept)
- Cannot create objects
- Supports multiple inheritance
4.4 Example
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}
4.5 Interface vs Abstract Class
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can have both | Mostly abstract |
| Inheritance | Single | Multiple |
5. Implementing Interfaces
5.1 implements Keyword
Used to implement an interface.
5.2 Example
interface Vehicle {
void start();
}class Car implements Vehicle {
public void start() {
System.out.println("Car starts");
}
}
5.3 Key Points
- Must override all methods
- Use
publicaccess
6. Multiple Interface Implementation
6.1 Definition
A class can implement more than one interface.
6.2 Example
interface A {
void show();
}interface B {
void display();
}class Test implements A, B {
public void show() {
System.out.println("Show method");
} public void display() {
System.out.println("Display method");
}
}
6.3 Advantages
- Achieves multiple inheritance
- Improves flexibility
Conclusion
Abstraction is a powerful concept that helps simplify complex systems by hiding unnecessary details. By using abstract classes and interfaces, developers can build flexible and scalable Java applications. Understanding abstraction is essential for mastering Object-Oriented Programming and real-world software design.
Leave a Reply