OOP.Abstraction

🎭 What is Abstraction?

let’s say we have 100 props of object in real world, but we need only 10 of them for our task, so we abstract from reality for our task.

Abstraction is the process of hiding the complex internal details of how something works and exposing only the essential features that users need to know. It helps focus on what an object does, rather than how it does it.


🔗 Simple Definition

“Show what, hide how.”


🔧 Example from Real Life

Think about a car.

  • When you drive, you only care about:
    • start() the engine
    • accelerate()
    • brake()
  • You don’t care how the engine works internally, how fuel is injected, or how the pistons move.
    The complex internal mechanics are hidden — that’s abstraction.

💻 Example in Code (Java)

abstract class Shape {
    abstract void draw();  // What to do (but no detail how to do it)
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a Circle");
    }
}

class Square extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a Square");
    }
}

Explanation

  • Shape defines what every shape should do — they must have a draw() method.
  • But how each shape draws itself is left to the individual subclasses (Circle, Square).
  • This way, the outside world only deals with Shape, without worrying about the internal details of each shape.

🔥 Why is Abstraction Important?

Reduces complexity — Users only see what they need.
Improves maintainability — Internal logic can change without affecting outside code.
Increases flexibility — Different implementations (like Circle and Square) can be swapped easily.
Supports polymorphism — Abstract classes and interfaces allow handling different types uniformly.


🔗 Abstraction vs. Encapsulation

ConceptWhat it does
AbstractionFocuses on hiding the implementation details and showing only necessary features.
EncapsulationFocuses on hiding data (fields) inside a class and exposing only controlled access via methods.

⚙️ How to Achieve Abstraction in Java?

  • Abstract Classes (partially abstract)
  • Interfaces (fully abstract)
This entry was posted in Без рубрики. Bookmark the permalink.