When should you use an abstract class rather than an interface, and what does the choice give you?
You use an abstract class when the child classes have something in common that is not just a list of method names. So when they share code, or share state, or when you want to control what they can do.
public class Main {
public static void main(String[] args) {
Repository r = new InMemoryRepository();
r.save("a");
System.out.println(r.read("a"));
}
}
And here is the abstract class and the implementation.
public abstract class Repository {
// The shared state.
protected final java.util.Map<String, String> data = new java.util.HashMap<>();
// The shared behaviour.
public void save(String key) {
data.put(key, readValue(key));
}
public abstract String readValue(String key);
public abstract void flush();
}
public class InMemoryRepository extends Repository {
@Override
public String readValue(String key) {
return data.get(key);
}
@Override
public void flush() {
System.out.println("nothing to flush");
}
}
So what does the choice give you? Four things that an abstract class gives you and an interface does not.
the gain why it matters
------------------------------------ --------------------------------------------
shared state the children can use the same
fields
shared code the children inherit the
behaviour and do not repeat it
a constructor the children must go through your
setup
control over the children you can leave a method abstract
and they must fill it in
And the third one is worth explaining, because it is the one that people forget. An abstract class can have a constructor, and so it can set up the state that every child needs. With an interface there is no constructor, so the setup has to happen in each child or in a helper object that the child holds.
And there are three reasons to choose the abstract class.
the reason why
------------------------------------------ --------------------------------------------
the children share real code so they do not repeat it
the children share state so it goes in the base class
you want to control what they can do so you leave a method
abstract
And there is one more thing that is worth knowing about, and it is the biggest practical difference. A class can only extend one class. So if you make the base an abstract class then that is the only base it will ever have. If you make it an interface then the class is free to extend something else as well.
// This class can have one base class and any number of
// interfaces.
public class InMemoryRepository extends AbstractRepository
implements Readable, Writable {
}
So the rule to remember is this. Use an abstract class for the shared code and state, and an interface when the only thing you share is the list of methods.
The last question in this topic lists the differences that matter in practice.