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 thing can do without saying how it does it. An interface is the most direct form of it, because an interface is a list of methods and nothing else.
public class Main {
public static void main(String[] args) {
Storage store = new FileStorage();
store.write("hello");
System.out.println(store.read("hello"));
}
}
And here is the interface and the class that implements it.
public interface Storage {
void write(String key, String value);
String read(String key);
}
public class FileStorage implements Storage {
private final java.util.Map<String, String> data = new java.util.HashMap<>();
@Override
public void write(String key, String value) {
data.put(key, value);
}
@Override
public String read(String key) {
return data.get(key);
}
}
So what does an interface give you that a concrete class cannot? Four things.
the gain what it means
-------------------------------- --------------------------------------------
the caller does not know the the code works with any implementation
implementation
the implementation can change the callers are not touched
the contract is written down the compiler checks that every
implementation has the methods
more than one thing can do it a collection can hold any of them
And the fourth one is the one that is not obvious. Once you have an interface type then you can hold several implementations in the same collection, and the code that works with them does not need to know what they are.
java.util.List<Storage> stores = new java.util.ArrayList<>();
stores.add(new FileStorage());
stores.add(new MemoryStorage());
for (Storage store : stores) {
store.write("key", "value"); // the same call, whichever one it is
}
And there is a fifth gain that is worth knowing about, and it comes from the compiler. If a class says it implements the interface then the compiler checks that every method is there with the right name and the right types. So a typo in a method name is a compile error and not a bug that shows up in production.
And an interface can also have default methods, so an interface can carry a small piece of shared behaviour. But the point of an interface is the list of promises, and the more behaviour you put into it the more you turn it back into a class.
So the rule to remember is this. An interface is the set of promises, and the caller holds the interface type so that the implementation can change.
The next two questions in this topic are about creating an interface and about leaking the implementation.