Sub topic 1
Why Abstraction? Describing What Without How
Think about a TV remote. You press the volume button and the sound gets louder. You do not need to know how the remote sends a signal or how the TV changes its speaker output. The button is a promise: "press me, and the volume goes up." The way that promise is kept stays hidden.
Programmers use the same idea all the time. This chapter explains what abstraction is, why it matters, and how Java supports it. Later chapters show the Java tools for it in detail.
What Abstraction Means
Abstraction is the practice of describing what something does while hiding how it does it. Code that uses a thing only needs to know its "what." The "how" can live somewhere else, and it can change without breaking anything.
Every piece of behavior has two sides:
| Side | Question it answers | Remote control example | Code example |
|---|---|---|---|
| The "what" | What can I ask for? | "Volume up" button | A method name, like `send(message)` |
| The "how" | How is it done? | Infrared signal, TV circuits | The code inside the method body |
The "what" is called the contract. A contract is a promise about which methods exist, what they take in, and what they give back. The "how" is called the implementation. An implementation is the actual code that keeps the promise.
A Problem Without Abstraction
Imagine an app that notifies users. At first it only sends emails. Later, the team adds text messages. Here is a version that has no shared contract:
class EmailSender {
void sendEmail(String text) {
System.out.println("Email: " + text);
}
}
class SmsSender {
void sendSms(String text) {
System.out.println("SMS: " + text);
}
}
public class Main {
static void notifyByEmail(EmailSender sender, String text) {
sender.sendEmail(text);
}
static void notifyBySms(SmsSender sender, String text) {
sender.sendSms(text);
}
public static void main(String[] args) {
notifyByEmail(new EmailSender(), "Your order shipped");
notifyBySms(new SmsSender(), "Your order shipped");
}
}This code runs. It prints:
Email: Your order shipped
SMS: Your order shippedLook at the cost, though:
- Both classes do the same job, but the method names differ (
sendEmailandsendSms). - The calling code needs a separate method for each kind of sender.
- Adding push notifications means writing a third class and a third
notifyBy...method. - Any code that calls
notifyByEmailmust change if the team switches to SMS.
The calling code knows too much about the "how." It is tightly coupled to each class. Tight coupling means one piece of code depends on the exact details of another, so a change in one forces changes in the other.
The Idea: Program to a Type, Not a Class
The fix is to write one contract, "a thing that can send a message," and make the calling code depend only on that. Then any sender that keeps the promise can be plugged in.
This habit is called programming to a type. A type here means a name for a set of promised behaviors. Your code holds a variable of the general type and does not care which specific class sits behind it.
The notification code talks only to the contract. You can add a new sender at the bottom without touching the code at the top.
You Already Use Abstraction in Java
The Java standard library is full of abstraction. A good example is List. List is a type that promises list behavior: add, get, size, and looping over items. Java ships several classes that keep this promise, including ArrayList and LinkedList. They store data in very different ways inside, but they offer the same methods.
In the code below, List<String> means "a list that holds strings." The part in angle brackets is called a type argument. It tells Java what kind of items the list holds.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Main {
static void printAll(List<String> items) {
for (String item : items) {
System.out.println("- " + item);
}
System.out.println("Count: " + items.size());
}
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("banana");
printAll(fruits);
List<String> colors = new LinkedList<>();
colors.add("red");
colors.add("green");
colors.add("blue");
printAll(colors);
}
}Output:
- apple
- banana
Count: 2
- red
- green
- blue
Count: 3Walk through what happened:
printAlltakes aList<String>. It does not mentionArrayListorLinkedListat all.- In
main,fruitsis declared as aListbut created as anArrayList. colorsis declared as aListbut created as aLinkedList.- The same
printAllmethod works for both, because both keep theListpromise.
If you later decide fruits should be a LinkedList, you change one word on one line. printAll stays the same. That is the payoff of abstraction.
Why Abstraction Matters
Abstraction gives you several practical benefits:
- Easier change. You can swap one implementation for another without editing the code that uses it.
- Less repeated code. One method, like
printAll, can serve many classes. - Simpler thinking. When you read calling code, you only need to understand the contract, not every detail behind it.
- Teamwork. One person can write code against a contract while another person writes the implementation at the same time.
- Easier testing. You can plug in a fake implementation during tests, such as a sender that records messages instead of really sending them.
Java's Two Tools for Abstraction
Java gives you two main ways to write a contract of your own. This tutorial covers each one in depth, so here is only a short preview:
| Tool | Short description | Covered in |
|---|---|---|
| Abstract class | A class that cannot be created directly. It can hold shared code and data, plus methods that subclasses must fill in. | The next few chapters |
| Interface | A pure list of promised methods that any class can sign up to keep. A class can keep many interfaces at once. | The chapters after abstract classes |
Both let you write code like printAll: code that depends on a general type and works with any class that keeps its promises. The last chapter of this tutorial explains how to choose between them.
Key Terms
- Abstraction: describing what something does while hiding how it does it.
- Contract: the promise a type makes about its methods.
- Implementation: the code that keeps the promise.
- Tight coupling: when code depends on the exact details of another class.
- Programming to a type: writing code against a general type instead of a specific class.
Exercise
In the List example, a teammate changes printAll(List<String> items) to printAll(ArrayList<String> items). Which call in main stops compiling, and why does this show the value of programming to a type?
Show answer
The call printAll(colors) stops compiling, because colors is declared as a List and holds a LinkedList, not an ArrayList. Once the parameter names a specific class, the method no longer accepts other lists that keep the same promise. Declaring the parameter as List<String> keeps the method open to every implementation.
Exercise
In the EmailSender and SmsSender example, name two problems caused by the lack of a shared contract, and describe what a shared contract would let the calling code do instead.
Show answer
Problems include different method names for the same job (sendEmail and sendSms), a separate notifyBy... method for each sender, and the need to edit calling code whenever a new sender is added or the team switches senders. With a shared contract such as "can send a message," the calling code could have one notify method that accepts any sender, and new senders could be added without changing it.
Exercise
Look at this line: List<String> names = new ArrayList<>();. Which part is the "what" and which part is the "how"?
Show answer
List<String> is the "what": it is the contract that says which methods names offers. new ArrayList<>() is the "how": it picks the class whose code actually stores and manages the items.