What is the difference between static and default methods in a Java interface?
Asked Answered
I

13

138

I was learning through interfaces when I noticed that you can now define static and default methods in an interface.

public interface interfacesample2 {
    public static void method() {
        System.out.println("hello world");
    }

    public default void menthod3() {
        System.out.println("default print");
    }
}

Kindly explain the difference of the two and also if there's an example of when we would use this would be nice. A little confused on Interfaces.

Indomitability answered 8/1, 2015 at 4:51 Comment(5)
Did you try reading up on static methods in the Java tutorial?Haymo
So you missed the part about not ever being able to override a static method?Haymo
didnt understand the same on interfacesIndomitability
static method is a static member to the Interface, cant be overridden (as with the class), default method is the default implementation of a method which might be overridden.Dualistic
Just wondering: why did you never accept an answer here?Culch
B
149

Differences between static and default methods in Java 8:

1) Default methods can be overriden in implementing class, while static cannot.

2) Static method belongs only to Interface class, so you can only invoke static method on Interface class, not on class implementing this Interface, see:

public interface MyInterface {
    default void defaultMethod(){
        System.out.println("Default");
    }

    static void staticMethod(){
        System.out.println("Static");
    }    
}

public class MyClass implements MyInterface {

    public static void main(String[] args) {

        MyClass.staticMethod(); //not valid - static method may be invoked on containing interface class only
        MyInterface.staticMethod(); //valid
    }
}

3) Both class and interface can have static methods with same names, and neither overrides other!

public class MyClass implements MyInterface {

    public static void main(String[] args) {

        //both are valid and have different behaviour
        MyClass.staticMethod();
        MyInterface.staticMethod();
    }

    static void staticMethod(){
        System.out.println("another static..");
    }
}
Brief answered 13/7, 2016 at 8:0 Comment(3)
but why 'static' ? what purpose does it serve in Java 8?Botulism
Purpose of static keyword doesn't changed-- to define class level members: fields, methods etc. In Java 8 this behavior was expanded to Interfaces, so they become more similar to classes and now can replace class in most scenarios.Brief
yea but we can still hide the interface static method instead of overriding,....i just think both fulfills the same purpose(use a common implementation) and resolves ambiguity by implementing the logic again in subclass (overriding,hiding). the only sensible reason would be due to the reason that[ static interface methods are not inherited](#25169675) and hence we cant call them using subclass instance.Gardia
A
31

A static method is a method that applies to the class 'namespace', so to speak. So a static method foo of interface Interface is accessed by Interface.foo(). Note that the function call does not apply to any particular instance of the interface.

A default implementation bar on the other hand, is called by

Interface x = new ConcreteClass();
x.bar();

A static interface method cannot know about the this variable, but a default implementation can.

Allwein answered 8/1, 2015 at 5:6 Comment(0)
D
21

1. explain the difference of the two

Static interface methods are like static class methods(here they belong to Interface only). Where as the default interface methods provide default implementation of interface methods (which implementing classes may override)
But remember in case a class is implementing more than one interface with same default method signature then the implementing class needs to override the default method

You can find a simple example below (can DIY for different cases)

public class Test {
    public static void main(String[] args) {
        // Accessing the static member
        I1.hello();

        // Anonymous class Not overriding the default method
        I1 t = new I1() {
            @Override
            public void test() {
                System.out.println("Anonymous test");
            }
        };
        t.test();
        t.hello("uvw");

        // Referring to class instance with overridden default method
        I1 t1 = new Test2();
        t1.test();
        t1.hello("xyz");

    }
}

interface I1 {

    void test();
    //static method
    static void hello() {
        System.out.println("hello from Interface I1");
    }

    // default need not to be implemented by implementing class
    default void hello(String name) {
        System.out.println("Hello " + name);
    }
}

class Test2 implements I1 {
    @Override
    public void test() {
        System.out.println("testing 1234...");
    }

    @Override
    public void hello(String name) {
        System.out.println("bonjour" + name);
    }
}

2. when we would use this would be nice.

That depends on your problem statement. I would say Default methods are useful, if you need same implementation for a method in your specification in all the classes in that contract, Or it may be used like Adapter classes.

here is a good read: https://softwareengineering.stackexchange.com/questions/233053/why-were-default-and-static-methods-added-to-interfaces-in-java-8-when-we-alread

also below oracle doc explains default & static methods for evolving existing interfaces:

Users who have classes that implement interfaces enhanced with new default or static methods do not have to modify or recompile them to accommodate the additional methods.

http://docs.oracle.com/javase/tutorial/java/IandI/nogrow.html

Dualistic answered 8/1, 2015 at 5:38 Comment(2)
I have a doubt. Is it possible to create a object of a interface? Your code has this line: I1 t = new I1()Comprise
@Comprise kindly read the java comment over that statement. Please also read about Anonymous classes. Hope that helps you.Dualistic
G
17

Here is my view:

static method in interface:

  • You can call it directly (InterfacetA.staticMethod())

  • Sub-class will not be able to override.

  • Sub-class may have method with same name as staticMethod

default method in interface:

  • You can not call it directly.

  • Sub-class will be able to override it

Advantage:

  • static Method: You don't need to create separate class for utility method.

  • default Method: Provide the common functionality in default method.

Gnatcatcher answered 5/6, 2018 at 18:4 Comment(0)
M
8

This link has some useful insights, have listed few of them here.

default & static methods have bridged down the differences between interfaces and abstract classes.

Interface default methods:

  • It helps in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.
  • It helps in extending interfaces without having the fear of breaking implementation classes.

Interface static methods:

  • They are part of interface, we can’t use it for implementation class objects.
  • It helps in providing security by not allowing implementation classes to override them.

Like to quote another useful reference.

Motherhood answered 15/12, 2015 at 3:15 Comment(0)
L
6

As per Java14 JLS doc:

Default Method:

  • It is an instance method declared in an interface with the default modifier

  • It can be accessed only by the instance of the implementing class only

  • Its body is always represented by a block, which provides a default implementation or behaviour for any implementing class without overriding the method

  • It can never be static or private

Static Method:

  • It can be invoked by interface without reference to a particular object, just like class static methods

  • Static method can be private

  • The implementing class can not access static method

Lets understand it with the help of below example code:

            public interface MyInterface {
        
            private void privateMethod() {
                System.out.println("Hi, this is privateMethod");
            }
        
            private static void staticPrivateMethod() {
                System.out.println("Hi, this is staticPrivateMethod");
            }
        
            static void staticMethod() {
                //privateMethod();    // Non-static method cannot be referenced from a static contex
                System.out.println("Hi, this is staticMethod");
                staticPrivateMethod();
            }
        
            default void defaultMethod() {
                System.out.println("Hi, this is defaultMethod");
            }
        
        }
    
    public class MyInterfaceImpl implements MyInterface{
        public static void main(String[] args) {
    
            MyInterface.staticMethod();
            // myInterface.staticMethod(); // Not allowed
    
            MyInterface myInterface = new MyInterfaceImpl();
            myInterface.defaultMethod();
            // MyInterface.defaultMethod(); // Not allowed
    
        }
    }

Lacustrine answered 24/7, 2020 at 16:4 Comment(0)
A
4

According to Oracle's Javadocs: http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

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.

Normally, static method in interface is used as Helper methods while default method are used as a default implementation for classes that implements that interface.

Example:

interface IDemo {

    //this method can be called directly from anywhere this interface is visible
    static int convertStrToInt(String numStr) {
       return Integer.parseInt(numStr);
    }


    //getNum will be implemented in a class
    int getNum();       

    default String numAsStr() {
       //this.getNum will call the class's implementation
       return Integer.toString(this.getNum());
    }   

}
Acidophil answered 8/1, 2015 at 5:46 Comment(0)
C
3

Interface default methods:

It helps in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.

It helps in extending interfaces without having the fear of breaking implementation classes.

Interface static methods:

They are part of interface, we can’t use it for implementation class objects.

It helps in providing security by not allowing implementation classes to override them.

Now how static method providing security. Let's see an example.

interface MyInterface {
    /*
     * This is a default method so we need not to implement this method in the implementation classes
     */
    default void newMethod() {
        System.out.println("Newly added default method in Interface");
    }

    /*
     * This is a static method. Static method in interface is similar to default method except that we cannot override them in the implementation classes. Similar to default methods, we need to implement these methods in implementation classes so we can safely add them to the existing interfaces.
     */
    static void anotherNewMethod() {
        System.out.println("Newly added static method in Interface");
    }

    /*
     * Already existing public and abstract method We must need to implement this method in implementation classes.
     */
    void existingMethod(String str);
}

public class Example implements MyInterface {
    // implementing abstract method
    public void existingMethod(String str) {
        System.out.println("String is: " + str);
    }

    public void newMethod() {
        System.out.println("Newly added default method in Class");
    }

    static void anotherNewMethod() {
        System.out.println("Newly added static method in Class");
    }

    public static void main(String[] args) {
        Example obj = new Example();

        // calling the default method of class
        obj.newMethod();
        // calling the static method of class

        obj.anotherNewMethod();

        // calling the static method of interface
        MyInterface.anotherNewMethod();

        // calling the abstract method of interface
        obj.existingMethod("Java 8 is easy to learn");

    }
}

Here obj.newMethod(); printing class implementation logic, means we can change the logic of that method inside implementation class.

But obj.anotherNewMethod(); printing class implementation logic ,but not changed interface implementation. So if any encryption-decryption logic written inside that method you can't change.

Cuyp answered 7/6, 2018 at 7:53 Comment(1)
this answer seems like it was going somewhere good,,then suddenly boom ! no meaningful explanation at the end. but not changed interface implementation what does this mean?Gardia
T
0

we cannot execute Interfacesample2.menthod3(); because it is not static method. In order to execute method3() we need an instance of Interfacesample2 interface.

Please find the following practical example:

public class Java8Tester {
   public static void main(String args[]){
      // Interfacesample2.menthod3(); Cannot make a static reference to the non-static method menthod3 from the type Interfacesample2

      new Interfacesample2(){ }.menthod3();// so in order to call default method we need an instance of interface

       Interfacesample2.method(); // it
   }
}

interface Interfacesample2 {
    public static void method() {
        System.out.println("hello world");
    }

    public default void menthod3() {
        System.out.println("default print");
    }
}
Troop answered 21/12, 2015 at 10:55 Comment(0)
F
0

Starting Java 8 interface can also have static method. Like static method of a class, static method of an interface can be called using Interface name.

Example

public interface Calculator {
    int add(int a, int b);
    int subtract(int a, int b);

    default int multiply(int a, int b) {
         throw new RuntimeException("Operation not supported. Upgrade to UltimateCalculator");
    }

    static void display(String value) {
        System.out.println(value);
    }
}

Difference between static and default method of interface is default method supports inheritance but static method does not. Default method can be overridden in inheriting interface.

Here is good read about interface default method and static method. Interface Default Method in Java 8

Fosterfosterage answered 21/8, 2019 at 22:58 Comment(0)
H
0

All good answers here. I would like to add another practical usage of the static function in the interface. The tip is coming from the book - Effective Java, 3rd Edition by Joshua Bloch in Chapter2: Creating and Destroying Object.

Static functions can be used for static factory methods. 

Static factory method are methods which return an object. They work like constructor. In specific cases, static factory method provides more readable code than using constructor.

Quoting from the book - Effective Java, 3rd Edition by Joshua Bloch

Prior to Java 8, interfaces couldn’t have static methods. By convention, static factory methods for an interface named Type were put in a noninstantiable companion class (Item 4) named Types.

Author gives an example of Collections where such static factory method is implemented. Checking on the code, Josh Bloch can be seen as first author of Collections class. Although Collections is a class and not interface. But the concept still applies.

For example, the Java Collections Framework has forty-five utility implementations of its interfaces, providing unmodifiable collections, synchronized collections, and the like. Nearly all of these implementations are exported via static factory methods in one noninstantiable class (java.util.Collections). The classes of the returned objects are all nonpublic.

Further he explains that API is not only smaller, it helps with the code readability and API ease..

It is not just the bulk of the API that is reduced but the conceptual weight: the number and difficulty of the concepts that programmers must master in order to use the API. The programmer knows that the returned object has precisely the API specified by its interface, so there is no need to read additional class documentation for the implementation class.

Here is one of the static method from java.util.Collections class:

public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
    return new UnmodifiableCollection<>(c);
}
Harper answered 25/10, 2019 at 3:18 Comment(0)
A
0

Static Interface Method:

  1. It is a static method which belongs to the interface only. We can write implementation of this method in interface itself.
  2. Static method can invoke only on interface class not on class.
  3. Interface and implementing class , both can have static method with the same name without overriding each other.
  4. It can be used as a utility method

Default Method:

  1. It is a method with default keyword and class can override this method.
  2. It can be invoked on interface as well as class.
  3. We can override the default method in implementing class.
  4. It can be used to provide common functionality in all implementing classes.

There is a link with detailed explanation. For detailed example: Default method vs static method in an interface in Java?

Astraddle answered 16/12, 2022 at 13:36 Comment(0)
V
0

Override: static method cannot be overridden in implementing class whereas we can override the default methods.

Access: static methods can be access via interface only, but default methods can be accessed via implementing classes as well.

Usage: static methods can be used as utility methods in interface while default methods can be used to share common functionality with all the implementing classes.

Visakhapatnam answered 4/3 at 14:19 Comment(2)
should be able to google this and find the answer. This is Java 101Chloe
I can't find anything in your answer that is not already mentioned in the other answers. What am I missing?Caustic

© 2022 - 2024 — McMap. All rights reserved.