Java Default or static method in Interface

Latest posts
Get notified of the Latest Sport News Update from Our Blog
Share

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

Your email address will not be published. Required fields are marked *

Related blogs

Nullam quis risus eget urna mollis ornare vel eu leo. Aenean lacinia bibendum nulla sed 

Subscribe to get 15% discount