Java - Instance Method References

Introduction

An instance method is invoked on an object's reference which is called the receiver of the method invocation.

The receiver can be an object reference or an expression that evaluates to an object's reference.

The following code shows the receiver of the length() instance method of the String class:

String name = "abcde";

// name is the receiver of the length() method
int len1 = name.length();

// "Hello" is the receiver of the length() method
int len2 = "Hello".length();

// (new String("abced")) is the receiver of the length() method
int len3 = (new String("abced")).length();

Type of Instance Method References

You can specify the receiver of the method invocation explicitly which is called a bound receiver.

Or you can provide it implicitly when the method is invoked which is called an unbound receiver.

Syntax

The syntax for an instance method reference supports two variants:

  • objectRef::instanceMethod
  • ClassName::instanceMethod

Related Topics