What is abstraction in object-oriented design, and what does an interface give you that a concrete class cannot?
Abstraction is the practice of describing what a component does without describing how it does it. The interface is its expression in Java: a named set of operations that says what callers can rely on and nothing more. A concrete class also has an abstraction, but it comes with an implementation attached, so callers end up depending on both the contract and the details.
public class Main {
public static void main(String[] args) {
Storage store = new FileStorage();
store.write("hello");
System.out.println(store.read());
Storage other = new FileStorage();
other.write(" world");
System.out.println(store.read());
}
}
interface Storage {
void write(String text);
String read();
}
class FileStorage implements Storage {
private String content = "";
public void write(String text) { content = content + text; }
public String read() { return content; }
}The output shows the two things an interface gives you. First, the reference type lets callers depend on the contract, so the same code can be pointed at a different implementation later without changing the caller. Second, the abstraction is enforced by the compiler, so a class that does not honour the contract cannot be used where the interface is expected.
The second point is where the interface really earns its keep. A caller written against Storage cannot accidentally depend on something FileStorage happens to have, because those extra methods are not visible through the interface. The contract is what the compiler checks and what the caller sees.
The cost to name honestly is that you have designed a promise. Every implementation has to honour it, and adding a method to the interface later breaks every implementor. That is a good reason to keep interfaces small and to add a second, focused interface rather than widening an existing one.