Abstraction in Java - Detailed Notes
What is Abstraction in Java?
Abstraction is the process of hiding internal implementation details and showing only the essential
features of an object.
It simplifies complex systems by modeling classes appropriate to the problem.
Real-Life Example:
You drive a car using the steering wheel and pedals, but you don't know how the engine works.
That's abstraction.
How is Abstraction Achieved in Java?
1. Abstract Classes
2. Interfaces
1. Abstract Class:
- Cannot be instantiated.
- Can have abstract and concrete methods.
Example:
abstract class Animal {
abstract void sound();
void eat() {
[Link]("This animal eats food.");
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
2. Interface:
- 100% abstraction.
- All methods are abstract by default (till Java 7).
Example:
interface Animal {
void sound();
class Cat implements Animal {
public void sound() {
[Link]("Cat meows");
Difference: Abstract Class vs Interface
- Abstract class can have constructors; interfaces cannot.
- Abstract class allows partial abstraction; interfaces allow full abstraction.
- Java supports multiple interfaces, but only one class extension.
How Abstraction Works:
1. Define contract using abstract class/interface.
2. Implement it in subclass.
3. Client uses the interface without worrying about implementation.
Combined Example:
interface Driveable {
void drive();
abstract class Vehicle {
abstract void start();
void stop() {
[Link]("Vehicle stopped.");
class Car extends Vehicle implements Driveable {
void start() {
[Link]("Car started.");
public void drive() {
[Link]("Car is being driven.");
Advantages of Abstraction:
- Hides complexity.
- Increases security.
- Supports loose coupling.
- Easier to maintain and extend.