πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

Default Methods in Interface  


Introduction
  • Default methods are methods in an interface that have a method body.
  • They were introduced in Java 8 to allow interfaces to have concrete methods without affecting classes that already implement the interface.
  • Declared using the default keyword.
  • They provide a way to add new methods to interfaces without breaking existing code that implements them.
  • Default methods are also known as defender methods or virtual extension methods.
  • Uses of Default Methods:
    • To add new functionality to an interface without forcing all implementing classes to override it.
    • To provide a default implementation that can be inherited by implementing classes.
    • To enable backward compatibility β€” old classes implementing the interface will still work even after new methods are added.
    • To support multiple inheritance of behavior (since a class can implement multiple interfaces with default methods).
Program:
  • Below is the program for Default methods in an Interface:
    interface MyInterface
    {
        // Abstract method (must be implemented by implementing classes)
        void m1();
    
        // Default method (has a body, optional to override)
        default void m2()
        {
            System.out.println("This is a default method inside an interface.");
        }
    }
    
    class MyClass implements MyInterface
    {
        @Override
        public void m1()
        {
            System.out.println("Implementation of abstract method.");
        }
    }
    
    public class MainApp1
    {
        public static void main(String[] args)
        {
            MyClass obj = new MyClass();
            obj.m1();   // Calls implemented abstract method
            obj.m2();   // Calls interface default
        }
    }