Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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:

  1. Use the default keyword to define an instance method with a body in an interface.
  2. Use the static keyword to define utility methods within the interface itself.
  3. 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.