Why abstraction?
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Abstraction is the fourth pillar of OOP. As What is OOP? (opens in a new tab) put it, you drive a car with the steering, brake and accelerator without knowing how the engine works. Java classes can be built the same way.
Show what, hide how
Abstraction is showing only what is needed to use an object and hiding how it works inside. In Java, a caller sees simple methods such as withdraw(amount), and the steps inside them stay hidden.
At an ATM you choose Withdraw, type the amount and take the cash. The PIN check, the balance check and the cash counter stay hidden. An Atm class can work the same way: one public method, hidden steps.
Example 1 · An ATM shows one action and hides the steps
class Atm { private int balance = 5000; private int pin = 1234;
void withdraw(int enteredPin, int amount) { if (!checkPin(enteredPin)) { System.out.println("Wrong PIN"); return; } if (amount > balance) { System.out.println("Not enough balance"); return; } balance = balance - amount; System.out.println("Please take Rs. " + amount); }
private boolean checkPin(int enteredPin) { return enteredPin == pin; }}
public class AtmDemo { public static void main(String[] args) { Atm atm = new Atm(); atm.withdraw(1111, 500); atm.withdraw(1234, 9000); atm.withdraw(1234, 2000); }}Wrong PIN Not enough balance Please take Rs. 2000
What this code does
mainknows onlywithdraw. The PIN check and the balance check are hidden inside the class: that is abstraction.checkPinisprivate, somaincould not call it even if it tried. Only the "what" is visible.balanceandpinareprivatetoo, so no one can change them from outside: encapsulation helping the abstraction.
In Java, the what is a set of method names with their parameters, like withdraw(pin, amount). The how is the code inside those methods and the private helpers they call. A UPI app is the same: you enter an ID, an amount and a PIN, and the bank-to-bank transfer stays hidden.
Callers depend only on the what
A ride app books an auto or a cab. If book knows only that every Ride has fare(km), the "how" of pricing can change, or new ride types can arrive, and book stays the same.
Example 2 · Same "what", different "how"
class Ride { int fare(int km) { return km * 10; }}
class AutoRide extends Ride { @Override int fare(int km) { return 30 + km * 15; }}
class CabRide extends Ride { @Override int fare(int km) { return 50 + km * 20; }}
public class BookingDemo { static void book(Ride r, int km) { System.out.println(km + " km: Rs. " + r.fare(km)); }
public static void main(String[] args) { book(new AutoRide(), 4); book(new CabRide(), 4); }}4 km: Rs. 90 4 km: Rs. 130
What this code does
bookonly knows that everyRidehasfare(km). It never asks how the price is worked out.- An auto and a cab price the same 4 km differently; a new ride type needs a new child class only, and
bookdoes not change.
This is the parent reference from Parent reference, child object (opens in a new tab), seen from the caller's side: book uses only the what. It also splits work in a team. One person writes the booking screen against fare, and others write each ride type without reading each other's code.
Abstraction vs encapsulation
Encapsulation hides an object's data; abstraction hides the steps behind a simple action. The two words sound alike and often appear together, but they answer different questions.
class Atm { private int balance = 5000; // encapsulation: hidden data
void withdraw(int pin, int amount) { // abstraction: one simple action if (!checkPin(pin) || amount > balance) { System.out.println("Cannot withdraw"); return; } balance = balance - amount; System.out.println("Take your cash: Rs. " + amount); }
private boolean checkPin(int pin) { return pin == 1234; }}What each one answers:
- Encapsulation, from Why encapsulation? (opens in a new tab): who may touch this data? Tools:
privatefields and checked methods. - Abstraction: what does the user of this class need to know? Tools: a few simple public methods, parent types, abstract classes and interfaces.
- They work together:
balanceis private (encapsulation) and onewithdrawhides the PIN and balance checks (abstraction).
The problem with a plain parent class
A parent Payment must have pay, but a general payment cannot really pay. So the parent gets a dummy body: a method that only prints something. Two things then go wrong, and Java warns about neither.
Example 3 · The weakness: a dummy body that runs silently
class Payment { void pay(int amount) { System.out.println("Paying Rs. " + amount + " somehow"); }}
class NetBanking extends Payment {}
public class DummyBodyDemo { public static void main(String[] args) { Payment p1 = new Payment(); p1.pay(300);
Payment p2 = new NetBanking(); p2.pay(700); }}Paying Rs. 300 somehow Paying Rs. 700 somehow
What this code does
new Payment()makes an object that is not any real payment type, and Java allows it.NetBankingforgot to overridepay, so the dummy body runs. The program compiles and prints nonsense, with no warning.
Example 4 · A first look at the fix: abstract
abstract class Payment { abstract void pay(int amount);}
class NetBanking extends Payment {}
public class AbstractPreviewDemo { public static void main(String[] args) { Payment p = new Payment(); p.pay(300); }}AbstractPreviewDemo.java:5: error: NetBanking is not abstract and does not override abstract method pay(int) in Payment
class NetBanking extends Payment {
^
AbstractPreviewDemo.java:10: error: Payment is abstract; cannot be instantiated
Payment p = new Payment();
^
2 errorsWhat this code does
abstract void pay(int amount);says "every payment must havepay", with no fake body.- Now javac catches both mistakes from the last example: the forgotten
payandnew Payment().
Java has two tools that fix this: abstract classes and interfaces. Both let you say "every payment must have pay" without a fake body, and the compiler then checks it. Abstract classes and abstract methods (opens in a new tab) explains each rule.
abstract and interface are the Java tools that put it into code.Next step
Check your understanding
11 quick questions