Java abstract classes and interfaces


Interfaces and abstract classes in Java have the potential to confuse novice programmers. While they have certain similarities they serve distinct purposes. Interfaces should be used to group behaviour and functionality that implementing types of this interface should expose, while abstract classes should be used as a basis for different subclasses. They come in handy, when you can already provide some fields and implementation to methods that all subclasses will have but cannot provide implementations to other methods, for which the subclasses will have to provide their own implementations.

Abstract classes allow you to declare fields which are not final or static. This means that an abstract class can declare state and not just behavior like an interface. Therefore, inheriting from an abstract class defines what you are instead of what you (can) do, which is what implementing an interface defines.

An interface can actually be regarded as a special case of an abstract class, without any non-final or non-static fields and only abstract methods (forgetting about default and static methods for now). While in abstract classes, abstract methods have to explicitly marked so with the abstract keyword, in interfaces all declared methods are by default abstract, and thus the abstract keyword can be omitted (It is not, however, wrong to include it, just uncommon).

If a class implements an interface but doesn't want to implement all of the methods it can do so by declaring itself abstract.

If an abstract class implements an interface it doesn't have to provide implementations for the interface methods (remember: interface method declarations are nothing else but abstract methods with the abstract keyword omitted for brevity.