What is the difference between data hiding and abstraction, and how do you see both in one class?
Data hiding is about the inside of one object. Abstraction is about the boundary between a caller and a collaborator. In the code above the internal list in ArrayStack is data hiding, because it is private and no caller can reach it. The Stack interface is abstraction, because it describes four operations without saying that the implementation happens to use a list.
public class Main {
public static void main(String[] args) {
Stack stack = new ArrayStack();
stack.push("a");
stack.push("b");
System.out.println(stack.size());
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.size());
}
}
interface Stack {
void push(String value);
String pop();
String peek();
int size();
}
class ArrayStack implements Stack {
private final java.util.List<String> items = new java.util.ArrayList<>();
public void push(String value) { items.add(value); }
public String pop() { return items.remove(items.size() - 1); }
public String peek() { return items.get(items.size() - 1); }
public int size() { return items.size(); }
}The output shows the value of having both. The caller pushes, peeks, pops and counts, and never learns that the implementation stores items in an ArrayList. If you later swapped that for a linked structure or for a database-backed implementation, the caller would not change, and the private list would simply be replaced.
Another way to see the difference is to ask what happens when the abstraction is missing. With data hiding but no abstraction, callers would depend on the concrete ArrayStack type, so swapping the implementation becomes a change across the codebase. With abstraction but no data hiding, the contract might be fine but the internals would be open to anyone, so nothing could enforce the rules.
The pairing is what makes change cheap. Data hiding lets you change the inside; abstraction stops the change from spreading. Used together, they are the practical core of object-oriented design.