Java Default or static method in Interface

Default Method

default method is used to provide common functionality to class. it can be override by implemented class.

Static Method

static method belongs to Interface, can’t override by class. interface and implemented class both can have static method with same name without overriding each other

interface MyInterface {
    // abstract method 
    public void fun3 ();

    // static method 
    static void fun1(){
        System.out.println("static function");
    }
    // default method 
    default void fun2(){
        System.out.println("Default Functionality ");
    }
}

to execute static function MyInterface.fun1();

public class Program1 implements MyInterface{

    // can have static function with the same name 
    static void fun1(){
        System.out.println("derkjek");
    }

    @Override
    public void fun3() {
        System.out.println("fun3");
    }

    public static void main(String[] args) {
        Program1 m1 = new Program1();
        // MyInterface.fun2(); can't call default method like this 
        m1.fun2(); //Default Functionality 

       // to call  static function 
        MyInterface.fun1(); 
        // m1.fun1(); // not worked 

    }
}

Leave a Reply