Java Abstraction

Java Abstraction

Abstraction in Java is one of the key Object-Oriented Programming (OOP) principles.
It hides internal implementation details and shows only the essential features to the user.


🔹 Why Use Abstraction?

  • To reduce complexity of the program.

  • To provide security by hiding implementation details.

  • To increase reusability and flexibility.


🔹 How is Abstraction Achieved in Java?

Java achieves abstraction in two ways:

Method Description
Abstract Classes Can have both abstract (unimplemented) and non-abstract (implemented) methods.
Interfaces All methods are abstract by default (before Java 8), used to achieve full abstraction.

🧩 1. Abstract Class Example

An abstract class cannot be instantiated (you cannot create objects of it).
It may contain abstract methods (no body) and defined methods (with body).

🔧 Example:

abstract class Animal {
// Abstract method
public abstract void sound();
// Regular method
public void sleep() {
System.out.println(“Animals sleep.”);
}
}

class Dog extends Animal {
public void sound() {
System.out.println(“Dog barks: Woof Woof!”);
}
}

public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
myDog.sleep();
}
}

✔ Output:

Dog barks: Woof Woof!
Animals sleep.

🧩 2. Interface Example

Interfaces provide 100% abstraction (before Java 8).
A class must implement all methods of an interface.

🔧 Example:

interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println(“Car is starting…”);
}

public void stop() {
System.out.println(“Car stopped.”);
}
}

public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
v.start();
v.stop();
}
}

✔ Output:

Car is starting...
Car stopped.

⚙ Abstract Class vs Interface

Feature Abstract Class Interface
Methods Can have abstract + non-abstract methods Only abstract (before Java 8)
Constructors Allowed Not allowed
Multiple Inheritance Not supported Supported
Variables Can be any type Always public static final (constants)

🎯 Real-Life Example of Abstraction

You use a TV remote without knowing the internal circuits.

Example:

abstract class Remote {
abstract void pressPowerButton();
}
class SamsungRemote extends Remote {
void pressPowerButton() {
System.out.println(“Samsung TV turned ON”);
}
}

public class Main {
public static void main(String[] args) {
Remote r = new SamsungRemote();
r.pressPowerButton();
}
}


🏁 Summary

  • Abstraction hides complexity and exposes only necessary functionality.

  • Achieved using abstract classes and interfaces.

  • Helps in clean, secure, and maintainable code.

You may also like...