Java Default and Static Methods in Interfaces – Complete Guide with Examples
Learn Java interface enhancements with default and static methods introduced in Java 8, including how to use them for code reuse and maintain backward compatibility with detailed examples.
Default and Static Methods in Interfaces – Complete Detailed Tutorial
Before Java 8, interfaces could only have abstract methods.
- Default methods and static methods were introduced in Java 8 to provide method implementations in interfaces without breaking existing code.
1. Default Methods in Interfaces
- Declared using the
defaultkeyword - Provides a method body inside the interface
- Can be overridden by implementing classes
- Helps in backward compatibility
Syntax:
2. Example – Default Method
Output:
Explanation:
Caroverrides the default methodBikeuses the default method provided by interface
3. Static Methods in Interfaces
- Declared using the
statickeyword - Called using interface name, not object reference
- Cannot be overridden by implementing classes
- Useful for utility methods related to interface
Syntax:
4. Example – Static Method
Output:
Explanation:
- Static methods are called using interface name
- Cannot be accessed through implementing class object
5. Advantages of Default and Static Methods
Default Methods:
- Provide method implementation in interfaces
- Maintain backward compatibility
- Can be overridden by implementing class
Static Methods:
- Provide utility/helper methods
- No need for object instantiation
- Improve modularity and code organization
6. Rules for Default and Static Methods
- Default methods can be overridden; static methods cannot
- Default method conflict resolution: if multiple interfaces have the same default method, class must override it
- Static methods cannot be called using class object, only using interface name
7. Example – Resolving Default Method Conflict
Output:
Explanation:
- When multiple interfaces have the same default method, implementing class must override
8. Summary
- Default methods: methods with implementation in interfaces, can be overridden
- Static methods: utility methods in interface, cannot be overridden
- Enables backward compatibility, code reuse, and modularity
- Essential for modern Java interface design