๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Static Methods in Interface  


Introduction
  • Static methods are methods in an interface that are declared using the static keyword.
  • They were introduced in Java 8 to allow interfaces to have utility/helper methods.
  • Static methods belong to the interface itself, not to the objects implementing the interface.
  • They can be called using the interface name without creating an object of the implementing class.
  • Static methods cannot be overridden by implementing classes.
  • Uses of Static Methods:
    • To define utility/helper methods inside interfaces, similar to static methods in classes.
    • To avoid creating separate utility classes for related helper functions.
    • To provide common functionality for all implementing classes without the need for overriding.
    • To keep related functionality encapsulated within the interface.
Program:
  • Below is the program for Static Methods in an Interface:
    interface MyInterface
    {
        // Abstract method (must be implemented by implementing classes)
        void m1();
    
        // Static method (can be called using interface name)
        static void m2()
        {
            System.out.println("This is a static method inside an interface.");
        }
    }
    
    class MyClass implements MyInterface
    {
        @Override
        public void m1()
        {
            System.out.println("Implementation of abstract method.");
        }
    }
    
    public class MainApp2
    {
        public static void main(String[] args)
        {
            MyClass obj = new MyClass();
            obj.m1();      // Calls implemented abstract method
    
            MyInterface.m2();   // Calling static method using interface name
        }
    }