Interfaces
Explore how Java interfaces define contracts for capabilities rather than inheritance, allowing unrelated classes to share behavior. Understand implementing interfaces, multiple inheritance of types, and the use of default methods. Learn when to choose interfaces over abstract classes to create flexible, decoupled designs that enhance modularity and scalability.
We can use abstract classes to share code and define templates for related objects. This works perfectly when objects share a strict is-a relationship, like a Dog being an Animal. But often we need to define a capability shared by objects that are completely unrelated. Consider a bird and an airplane: both can fly, but they do not belong to the same family tree. If we tried to force them under a common Flyer superclass, we would create a messy, confusing hierarchy.
Java solves this with interfaces, a mechanism that defines what an object can do, regardless of its type. By using interfaces, we create flexible contracts that decouple our code from specific implementation details.
Defining a contract with interfaces
An interface is a contract that specifies a set of methods that a class must implement. Unlike a class, an interface does not describe how behavior is performed; it only describes what that behavior looks like.
We define an interface using the interface keyword. Inside, we declare methods without bodies. By default, these methods are implicitly public and abstract. We do not need to type these keywords, though knowing they are there helps us understand the rules.
Interfaces can also contain constant values. Any variable declared in an interface is implicitly public, static, and final.
Here is how we define a simple contract for objects that can be saved to a database:
Line 2: We use the
interfacekeyword to define a contract that specifies what a class must do, rather than how it does ...