Java 8: Method references

  Java Features     Java 5     Java 7     Java 8  
Java 8 features
 Lambda expressions |   Method references |   Default methods |   forEach loop |   By date 

The feature method references is included in JSE8. The lambda expression is used sometimes to create anonymous methods. When a lambda expression only invoke an existing method, it is better to refer the method by using its name. For more info click here to read Oracle’s explanation.

Kinds of method references

  1. Reference to a static method: Class::static method name.
  2. Reference to an instance method: Object::instance method name.
  3. Reference to a constructor: Class name::new.

Example: Reference to a static method

Example 1: Java method references

What happens if the following code is compiled and run?

MsInterface.jave

public interface MsInterface
{
  void print(String message);
}

Employee.java

public class Employee
{
  public static void getMessage(String m)
  {
    System.out.println("Name: " + m);
  }
  public static void main(String[] args)
  {
    // A static method reference
    MsInterface ms = Employee::getMessage;
    /* Invoking the interface
     *  method print
     */
    ms.print("Emma.");
  }
}

Author: Sar Maroof

Select the correct answer.


Answer explanation

We passed the name Emma to the method print. So, the statement System.out.println(“Name:  ” + message); writes: Name: Emma. to the standard output.

The correct answer is: a.





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

1 Comment

Add a Comment
  1. We passed the name Emma to the method print. So, the statement System.out.println(“Name: ” + message); writes: Name: Emma. to the standard output.
    Print in turn calls the static method getMessage with argument as m and this is possible because of Java8

Leave a Reply

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