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
Shapemust provide its own version of thedraw()method.
Breakdown of your Shape example:
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 ofclass) andimplements(instead ofextends).Rules: All methods in an interface are automatically
publicandabstract.
Example of an Interface:
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.
| Feature | Abstract Class | Interface |
| Methods | Can have both abstract and regular methods. | Can only have abstract methods (mostly). |
| Variables | Can have final, non-final, static variables. | Can only have static and final variables. |
| Inheritance | A class can extend only one abstract class. | A class can implement multiple interfaces. |
| Keyword | abstract | interface |
4. Why use Abstraction?
Security: You hide the internal implementation.
Standardization: You force all subclasses to follow the same method names (like
draw()), making the code organized.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.