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.
In simple words:
Interface is a contract that a class must follow.
What is an Interface?
- An interface is declared using the keyword interface
- It contains abstract methods (by default)
- A class uses implements keyword to implement an interface
- Object cannot be created for an interface
Why Use Interface 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();
}
- After Java 8, interfaces can have 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 call using
InterfaceName.super.methodName();
Important Rules of Interface
- All methods are public and abstract by default
- Variables are public static final (constants)
- Interface methods must be implemented by the class
- A class can implement multiple interfaces
- Interface cannot have constructors
Top comments (0)