How do you hide implementation details in Java, and what is the difference between hiding them with access modifiers and hiding them behind an interface?
You hide a detail with an access modifier when the detail belongs to one class, and you hide it behind an interface when the detail belongs to one of several implementations.
public class Main {
public static void main(String[] args) {
NameStore store = new MapNameStore();
store.put("ada", "Ada");
System.out.println(store.get("ada"));
}
}
And here is the interface and the implementation.
public interface NameStore {
void put(String key, String name);
String get(String key);
}
public class MapNameStore implements NameStore {
private final java.util.Map<String, String> names = new java.util.HashMap<>();
@Override
public void put(String key, String name) {
names.put(key, name);
}
@Override
public String get(String key) {
return names.get(key);
}
}
So what is the difference between the two ways of hiding?
the way what it hides who it hides it from
------------------------- -------------------------- ------------------------
the access modifier the members of one class the classes that call it
the interface the whole implementation everyone, including the
future implementations
And the difference comes down to how many implementations there are. If there is only one class and it will always be the only one, then a private field is enough and an interface is overhead. If there is more than one, or if you want to be able to add another one without changing the callers, then the interface is what does the hiding.
And there is a third thing worth knowing about. The access modifier hides the members but the type is still visible. So if a method returns a MapNameStore then the caller can see the class even if it cannot see its fields. An interface hides the type as well, so the caller only ever sees the interface.
// The caller can see the type.
public MapNameStore createStore() {
return new MapNameStore();
}
// The caller only sees the contract.
public NameStore createStore() {
return new MapNameStore();
}
And there are the ways that you hide a detail in Java, and here they all are.
the tool what it hides
-------------------------- --------------------------------------------
a private field the data itself
a private method a helper that callers should not use
a package-private method a helper for the classes in the package
an interface the whole implementation
a copy that you return the live data, so the caller cannot
change it
So the rule to remember is this. Private hides the members of one class, and an interface hides the implementation from everybody.
The next two questions in this topic are about returning a cache and about the plain meaning.