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
- Reference to a static method: Class::static method name.
- Reference to an instance method: Object::instance method name.
- 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
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.
Suggested Articles
![]() ![]() ![]() |
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