Sub topic 1
Why Abstraction? Describing What Without How
Think about driving a car. You press the pedal and the car moves. You do not need to know how the engine burns fuel. The pedal tells you what the car can do. The engine handles how it does it.
Java code works the same way. This chapter explains the idea behind abstract classes and interfaces before you learn how to write them.
What Abstraction Means
Abstraction is a way of hiding details. You show only what something does and keep how it does it out of sight.
A type is a name for a kind of value, like String or int. When you write code that uses a type, you rely on the methods that type promises to have.
Programming to a type means you write code that depends on what a type promises, not on one exact class. Your code then works with any class that keeps those promises.
Why It Matters
Abstraction helps you in three ways:
- Simpler code. You only think about what you need, not every detail.
- Easy changes. You can swap one class for another without rewriting the code that uses it.
- Teamwork. One person can write the "how" while another uses the "what".
A Worked Example
Java already uses abstraction in its own library. List is a type that promises methods like add and size. ArrayList and LinkedList are two classes that keep those promises in different ways.
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("pear");
printAll(fruits);
List<String> colors = new LinkedList<>();
colors.add("red");
printAll(colors);
}
}The method printAll asks for a List. It does not care which kind of list it gets. Both calls work because both classes do what List promises.
Java's Two Tools
Java gives you two tools for describing "what" without "how":
| Tool | Short description |
|---|---|
| Abstract class | A partly finished class that other classes complete |
| Interface | A list of methods a class promises to provide |
You will learn to write both in the next chapters.
Exercise
In the example, why can printAll accept both an ArrayList and a LinkedList?
Show answer
Because printAll asks for the type List, and both classes provide every method List promises. The method depends on what a list can do, not on how a particular class does it.
Exercise
Give one everyday example of abstraction and name its "what" and its "how".
Show answer
A TV remote is one example. The "what" is the buttons: power, volume, channel. The "how" is the electronics inside the TV that respond to those buttons.