What is Abstraction?

Abstraction is the process of hiding the implementation details and showing only the functionality.

Real-life Example: When you ride a bike, you know that turning the handle turns the bike and pressing the brakes stops it. You don’t need to know the internal mechanics of how the brake cable pulls the pads or how the engine combustion works to ride it. That internal complexity is abstracted away.


1. Abstract Classes

An abstract class is a restricted class that cannot be used to create objects (you cannot say new Shape()). To access it, it must be inherited from another class.

  • Abstract Method: A method that has no body (no { }). It only has a signature.

  • Purpose: It defines a “contract.” Any class that inherits from Shape must provide its own version of the draw() method.

Breakdown of your Shape example:

Java

 
abstract class Shape {
    abstract void draw(); // No body! Each shape draws differently.

    void message() { // Abstract classes can also have regular methods
        System.out.println("Preparing to draw...");
    }
}

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

2. Interfaces

An Interface is a completely “abstract class” that is used to group related methods with empty bodies. While a class can only extend one parent, it can implement multiple interfaces.

  • Keyword: interface (instead of class) and implements (instead of extends).

  • Rules: All methods in an interface are automatically public and abstract.

Example of an Interface:

Java

 
interface Animal {
    void animalSound(); // Interface method
}

class Pig implements Animal {
    public void animalSound() {
        System.out.println("The pig says: wee wee");
    }
}

3. Abstract Class vs. Interface

This is the most popular question in university exams regarding Abstraction.

FeatureAbstract ClassInterface
MethodsCan have both abstract and regular methods.Can only have abstract methods (mostly).
VariablesCan have final, non-final, static variables.Can only have static and final variables.
InheritanceA class can extend only one abstract class.A class can implement multiple interfaces.
Keywordabstractinterface

4. Why use Abstraction?

  1. Security: You hide the internal implementation.

  2. Standardization: You force all subclasses to follow the same method names (like draw()), making the code organized.

  3. Flexibility: You can change the internal logic of a subclass without affecting the rest of the system.


Summary for Students

  • Abstraction is about “What an object does” rather than “How it does it.”

  • Use an Abstract Class if you want to share some code (regular methods) but force others (abstract methods).

  • Use an Interface if you want to define a total “contract” or behavior that many different classes might use.