Java 8 FAQ: Top Questions
6. What are default and static methods in interfaces in Java 8?
Java 8 introduced default and static methods in interfaces to allow method implementations without breaking existing code. These additions improve code reuse and interface evolution.
πΊοΈ Step-by-Step Instructions:
- Use the
default
keyword to define an instance method with a body in an interface. - Use the
static
keyword to define utility methods within the interface itself. - Call static methods using the interface name.
π₯ Example Input:
interface Vehicle {
default void start() {
System.out.println("Starting vehicle...");
}
static void info() {
System.out.println("Vehicle interface");
}
}
π Expected Output:
Starting vehicle...
Vehicle interface
β Java 8 Solution:
public class Car implements Vehicle {
public static void main(String[] args) {
Car car = new Car();
car.start(); // Calls default method
Vehicle.info(); // Calls static method
}
}
interface Vehicle {
default void start() {
System.out.println("Starting vehicle...");
}
static void info() {
System.out.println("Vehicle interface");
}
}
π Detailed Explanation:
- Default methods: Allow new functionality in interfaces without affecting implementing classes.
- Static methods: Useful for utility functions related to the interface.
- Multiple Inheritance Conflict: If two interfaces provide default methods with the same signature, the implementing class must override it explicitly.
π οΈ Use Cases:
- Backward compatibility when evolving APIs.
- Providing shared logic among interface implementers.
- Encapsulating helper methods directly within the interface.