An interface is a blueprint that defines what methods a class must have.
Interfaces are used for abstraction. This means they describe what a class should do without fully explaining how it should do it.
A class uses the implements keyword to follow an interface.
When a class implements an interface, it must provide code for the interface methods.
You can use an interface type as a reference variable. This allows your code to work with many different classes that implement the same interface.
In this example, Animal is the reference type, but the actual object is a Dog.
Java does not allow a class to extend multiple classes, but one class can implement multiple interfaces.
This is useful when a class needs to support multiple behaviors, such as flying and swimming.
Interfaces can include default methods. A default method has a body and can be used directly by classes that implement the interface.
A class can also override the default method if it needs custom behavior.
Interfaces can also have static methods. These methods belong to the interface itself, not to an object.
To call a static interface method, use the interface name followed by the method name.
Classes and interfaces are both used to organize code, but they have different purposes.
A class usually stores data and behavior. An interface focuses on defining behavior that other classes must follow.
Interfaces make your code more flexible because different classes can follow the same structure while having different implementations.
For example, an Employee and a Freelancer can both be Payable, even if their pay is calculated differently.
Create an interface called Payable with a method calculatePay(). Then create Employee and Freelancer classes that implement it.