Default Methods


Idioms and Techniques

Design Rationale

Advanced Questions

What is the syntax for instance method references?

The syntax for referring to static methods has been described. There are two ways of referring to instance methods. One is strictly analogous to the static case, replacing the form ReferenceType::Identifier with ObjectReference::Identifier. For example, the forEach method could be used to pass each element from a collection into an instance function for processing:


This is not the most useful variant of instance method references, however; the argument to forEach (or any other method accepting a function in this way) cannot refer to the element that it is processing. Rather, supposing that the elements of pointList belonged to a class TransPoint having a method

    void transpose () { int t = x; x = y; y = t; };

we often want to write something of this form:

    pointList.forEach(/*transpose x and y of this element*/);

The second syntactic variant of instance method references supports this usage. The form


—where a reference type rather than an object reference is used in conjunction with an instance method name—is translated by the compiler into a lambda expression like this:

    (TransPoint pt) -> { pt.transpose(); }

—that is, a lambda expression is synthesized with a single parameter that is then used as the receiver for the call of the instance method. So the syntax


achieves the result we wanted. The same transformation can be applied to instance methods with any number of parameters; in each case, an extra parameter, representing the receiver, is inserted before the invocation parameters.
foreach takes a function and applies
it to every element (see this page).