Java Interfaces and Multiple Inheritance – Complete Guide with Examples
Learn Java interfaces, how to implement multiple inheritance using interfaces, default and static methods, and achieve flexibility and modularity in object-oriented programming.
Interfaces and Multiple Inheritance in Java – Complete Detailed Tutorial
Interfaces in Java are abstract types that allow a class to implement multiple sets of methods, achieving multiple inheritance.
They define method signatures without implementation (except default and static methods).
1. Key Points About Interfaces
- Declared using the
interfacekeyword - Can have abstract methods (no body)
- Can have default methods with body (Java 8+)
- Can have static methods with body
- Cannot be instantiated
- A class can implement multiple interfaces
- Supports multiple inheritance, unlike classes
2. Syntax of an Interface
- Implemented using
implementskeyword:
3. Example – Basic Interface Implementation
Output:
4. Multiple Inheritance Using Interfaces
- Java does not support multiple inheritance with classes to avoid ambiguity
- Interfaces allow multiple inheritance
Example:
Output:
Explanation:
- Class
Cimplements multiple interfacesAandB - Resolves multiple inheritance issue
5. Default and Static Methods in Interfaces (Java 8+)
- Default methods → have body, can be overridden in implementing class
- Static methods → called using interface name
Example – Default & Static Methods:
Output:
6. Key Points of Interfaces
- Used for multiple inheritance
- Can contain abstract, default, and static methods
- Helps in loose coupling and modularity
- Promotes polymorphism (interface reference can point to multiple implementations)
7. Summary
- Interface → abstract type for method signatures
- Allows multiple inheritance, unlike classes
- Supports default and static methods
- Provides flexibility, modularity, and polymorphism in OOP