Method References to Instance Methods

Java-Method References

Method References

A method reference provides a way to refer to a method without executing it. It relates to lambda expressions because it, too, requires a target type context that consists of a compatible functional interface. When evaluated, a method reference also creates an instance of the functional interface. There are different types of method references, Method References to static Method, Method References to Instance Methods.

Method References to static Method

To create a static method reference, use the syntax: ClassName::staticMethodName. Notice that the class name is separated from the method name by a double colon. The :: is a separator that was added to Java by JDK 8 expressly for this purpose. This method reference can be used anywhere in which it is compatible with its target type.

The following program demonstrates a static method reference. Notice the first line in the main( ), a reference to the static method myOldMobile( ), declared inside Javaapp, is passed as argument to showMyMobile( ). This works because myOldMobile( ) is compatible with the Mobile functional interface. Thus, the expression Javaapp::myOldMobile evaluates to a reference to an object in which myOldMobile( ) provides the implementation of myMobile( ) in Mobile.

Program

Method-References

Program Source

interface Mobile {

    String myMobile();
}
class Javaapp {

    static String myOldMobile() {

        return "Old : Samsung Galaxy S6";
    }
    static String myNewMobile() {

        return "New : Samsung Galaxy S9";
    }
    static void showMyMobile(Mobile mo) {
        
        System.out.println(mo.myMobile());
    }
    public static void main(String[] args) {

        showMyMobile(Javaapp::myOldMobile);
        showMyMobile(Javaapp::myNewMobile);
    }
}

Leave a Comment