Difference between default and static interface method in Java 8.

JavaObject Oriented ProgrammingProgramming

According to Oracle's Javadocs −

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.

Static method in interface are part of the interface class can’t implement or override it whereas class can override the default method.

Sr. No.KeyStatic Interface MethodDefault Method
1
Basic
It is a static method which belongs to the interface only. We can write implementation of this method in interface itself
It is a method with default keyword and class can override this method
2
Method Invocation
Static method can invoke only on  interface class not on class.
It can be invoked on interface as well as class
3
Method Name
Interface and implementing class , both can have static method with the same name without overriding each other.
We can override the default method in implementing class
4.
Use Case
It can be used as a utility method
It can be used to provide common functionality in all implementing classes

Example of Default and Static method in interface

public interface DefaultStaticExampleInterface {
   default void show() {
      System.out.println("In Java 8- default method - DefaultStaticExampleInterface");
   }
   static void display() {
      System.out.println("In DefaultStaticExampleInterface I");
   }
}
public class DefaultStaticExampleClass implements DefaultStaticExampleInterface {
}
public class Main {
   static void main(String args[]) {
      // Call interface static method on Interface
      DefaultStaticExampleInterface.display();
      DefaultStaticExampleClass defaultStaticExampleClass = new DefaultStaticExampleClass();
     
      // Call default method on Class
      defaultStaticExampleClass.show();
   }
}
raja
Published on 09-Sep-2020 11:37:56
Advertisements