What is the difference between data hiding and abstraction, and how do you see both in one class?
Data hiding is about keeping the data of one object private. Abstraction is about giving the caller a simple shape and not letting them know what is behind it. You can see both in one class.
public class Main {
public static void main(String[] args) {
Stack stack = new ArrayStack();
stack.push("a");
stack.push("b");
System.out.println(stack.pop()); // b
System.out.println(stack.size()); // 1
}
}
And here is the class, and you can see both ideas in it.
public class Stack {
private final java.util.List<String> items = new java.util.ArrayList<>();
public void push(String item) {
items.add(item);
}
public String pop() {
if (items.isEmpty()) {
throw new IllegalStateException("stack is empty");
}
int last = items.size() - 1;
String value = items.get(last);
items.remove(last);
return value;
}
public int size() {
return items.size();
}
}
So where is the data hiding? The field items is private, so the caller cannot get at the list and cannot change it or replace it. That is data hiding.
And where is the abstraction? The caller sees only push, pop and size, and they do not know that the list is used to hold the items. If you changed the list into an array tomorrow, the caller would not notice. That is abstraction.
the question the idea
------------------------------------ ----------------------------------
can the caller touch the data? data hiding, the answer is no
does the caller need to know how abstraction, the answer is no
it works?
And they are two different ideas that happen to appear in the same class, because the usual way to get an abstraction is to hide the data behind it.
the class the data hiding the abstraction
-------------- --------------------- -------------------------------
Account the balance is private withdraw and deposit
Stack the list is private push and pop
Cart the items are private add and total
And there is one case where you can have one without the other, and it is worth knowing about. You can hide the data without giving a useful abstraction. So a class with a private field and a getter and a setter has data hiding, but the abstraction is no better than a public field because the caller can still do anything with the value.
And the opposite case is rarer. You can have a nice abstraction with no data hiding at all if the class has no data. So a class that just computes something and holds no state has an abstraction and nothing to hide.
So the rule to remember is this. Data hiding is about the inside of the object, and abstraction is about the view that the outside has.
The last question in this topic is about whether the two are the same thing.