← Back to Chapters

Java Abstraction

? Java Abstraction

? Quick Overview

Abstraction in Java is an OOP concept that focuses on hiding internal implementation details and showing only essential features to the user. It helps reduce complexity and increase maintainability.

? Key Concepts

  • Achieved using abstract classes and interfaces
  • Shows what an object does, not how
  • Improves code security and flexibility

? Syntax / Theory

An abstract class can have abstract and non-abstract methods. Abstract methods do not have a body and must be implemented by child classes.

? Code Example

? View Code Example
// Abstract class defining common behavior
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Animal is sleeping");
}
}

// Child class providing implementation
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}

// Main class to test abstraction
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
a.sleep();
}
}

? Live Output / Explanation

Output

Dog barks
Animal is sleeping

The reference variable of abstract type calls the implementation provided by the child class.

? Interactive Simulation

The code calls animal.sound(), but the implementation changes based on the object you create.

Animal myPet = new Dog();
myPet.sound();
? Output: "Dog barks"

✅ Tips & Best Practices

  • Use abstraction to define common templates
  • Prefer interfaces for full abstraction
  • Keep abstract methods minimal

? Try It Yourself

  • Create an abstract class Shape with method draw()
  • Implement it using Circle and Rectangle classes
  • Call methods using abstract reference