Home Core Java Java 8 - Method Reference

Java 8 – Method Reference

In this guide, we will look into what is Java 8 Method Reference and various kinds of referencing a method with basic examples.

1. What is method reference in Java 8?

To create lambda expressions we use anonymous methods. Some times the implementation that you want to create in lambda is already available in existing method. In those cases method references enable you to refer functional interface method by name in place of lambda expressions.

Our specified method can be either static method or instance method. Functional interface method and our specified method should have same argument and compatible return types, except this remaining things like method name, modifiers are not required to match.

2. Various kinds of referencing a method

  1. Reference to static method.
  2. Reference to an instance method of a particular object.
  3. Reference to an instance method of an arbitrary object of a particular type
  4. Reference to a Constructor

To define method reference we have to use :: (double colon) operator.

java method reference

3. Reference to static method

You can refer to static method defined in the class. Following is the syntax and example which describe the process of referring static method in Java.

Syntax:

 <target class name>::<static method name>

3.1. Example with lambda expression

@FunctionalInterface
interface MyFunctionalInterface {
    
    boolean isEvenNumber(int i);
}
 
public class MethodReferenceDemo {
 
    public static void main(String[] args) {
        //Lambda Example
        MyFunctionalInterface mi = i -> i%2 == 0;
        
        System.out.println(mi.isEvenNumber(15));//false
        System.out.println(mi.isEvenNumber(20));//true
    }
}

3.2. Same example with reference to a method

@FunctionalInterface
interface MyFunctionalInterface {
    
    boolean isEvenNumber(int i);
}
 
public class MethodReferenceDemo {
    
    static boolean myImplementation(int i) {
        
        return i%2 == 0;
    }
 
    public static void main(String[] args) {
        
        MyFunctionalInterface mi = MethodReferenceDemo::myImplementation;
        
        System.out.println(mi.isEvenNumber(15));//false
        System.out.println(mi.isEvenNumber(20));//true
    }
}

4. Reference to an instance method

Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax:

<target class object>::<instance method>

4.1. Reference to instance method example

@FunctionalInterface
interface MyFunctionalInterface {
 
    boolean isEvenNumber(int i);
}
 
public class MethodReferenceDemo {
    
    //instance method
    boolean myImplementation(int i) {
        
        return i%2 == 0;
    }
 
    public static void main(String[] args) {
        
        MethodReferenceDemo demo = new MethodReferenceDemo();
        MyFunctionalInterface mi = demo::myImplementation;
        
        MyFunctionalInterface mi2 = new MethodReferenceDemo()::myImplementation;
        
        System.out.println(mi.isEvenNumber(15));//false
        System.out.println(mi2.isEvenNumber(20));//true
    }
}

5. Reference to an instance method of an arbitrary object of a particular type

Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax:

<arbitary object type>::<instance method>

Look into the example, String::toUpperCase, usually toUpperCase() method is called on a string reference but we have written class name “String” as like reference to static method.

In the following example, String is particular type and the arbitrary object is the instance of String that is used during method invoke. When reference to an instance method of an arbitrary object of a particular type, that invokes a method onto the current object.

5.1. Example 1

@FunctionalInterface
interface MyFunctionalInterface {
    
    String processString(String name);
}
 
public class MethodReferenceDemo {
    
    public static void main(String[] args) {
        
        MyFunctionalInterface f1 = s -> s.toUpperCase();
        System.out.println(f1.processString("Peter")); // PETER
    	
    	// Above two lines equalant to following lines
        MyFunctionalInterface f2 = String::toUpperCase;
        System.out.println(f2.processString("Peter")); // PETER
    }
}

5.2. Example 2

public class Student {

	private String name;
	private Integer id;

	public Student(String name) {
		this.name = name;
	}

	public String getUppercaseName() {
		return name.toUpperCase();
	}	
	
	public void printLowerCaseName() {
		System.out.println(name.toLowerCase());
	}
}
@FunctionalInterface
interface StudentFunctionalInterface {
    
    String getStudentName(Student student);
}
public class MethodReferenceArbitaryObjectDemo {
    
    public static void main(String[] args) {
        
    	StudentFunctionalInterface f = Student::getUppercaseName;
        System.out.println(f.getStudentName(new Student("Peter"))); // PETER
        
        final List<Student> students = Arrays.asList(
        		                              new Student("Mike"),
        		                              new Student("John"),
        		                              new Student("Martin")
        		                              );
        
        students.forEach(Student::printLowerCaseName);
    }
}

Output :

PETER
mike
john
martin

6. Conclusion

In this article we covered reference to various kinds of methods with examples using Java 8. As constructors also special kind of methods, they execute at the time of object initialization, Java constructor reference also possible.

7. References

  1. Java documentation
  2. Java Double Colon Operator
  3. Java 8 Constructor reference

LEAVE A REPLY

Please enter your comment!
Please enter your name here