An interface is a contract.
It contains:
- Constants (implicitly
public static final). - abstract methods (implicitly
public). - Default methods (with a body).
- static methods (with a body, called as
Interface.method()).
It cannot contain:
- instance attributes
- constructors
you cannot instantiate an interface.
Using interfaces:
- A class
implementsone or more interfaces. - An interface
extendsother interfaces. - The order
class X extends Y implements A, B. - The implementing class must implement every method, unless the class is itself abstract.
Default method conflict:
- If two interfaces provide the same default method, the class mut override it. Inside the override it can call
A.super.show()to pick one.
Interface as a type:
MakeSoundInterface m = new CuckooClock()works. This lets unrelates classes (Dog - CukooClock) be treated alike. Useinstanceofbefore casting.
Evolving an interface safely:
- add a new interface that extends the old one, or add the new methods as default or static methods. Either way, existing implementers don’t break.
Abstract class vs Interface:
- An abstract class holds shared state and behavior within one hierarchy.
- An interface defines shared behavior across unrelated classes.