Interface in Java
Source: Dev.to
Introduction
An interface in Java is used to achieve abstraction and multiple inheritance. It defines what a class should do, but not how it should do it.
What is an Interface?
- Declared using the
interfacekeyword. - Contains abstract methods (by default).
- A class uses the
implementskeyword to implement an interface. - Objects cannot be created directly from an interface.
Why Use Interfaces in Java?
- To achieve abstraction.
- To support multiple inheritance.
- To achieve loose coupling.
- To define common behavior for unrelated classes.
Syntax
interface InterfaceName {
void method1();
void method2();
}
Default Methods (Java 8+)
After Java 8, interfaces can include default methods. If a class implements two interfaces that contain default methods with the same signature, the class must override the method and explicitly specify which interface method to invoke:
InterfaceName.super.methodName();
Important Rules of Interfaces
- All methods are
publicandabstractby default. - Variables are
public static final(constants). - Interface methods must be implemented by the implementing class.
- A class can implement multiple interfaces.
- Interfaces cannot have constructors.