Skip to content

Methods on the parameter, and constructors

โ˜• Java 17 ยท Passing Methods Around by Name ยท 2/3

Shapes 1 and 2 call a static method or a method on an object you already have. The last two shapes work differently.

Shape 3 โ€” The parameter becomes the object

interface TitleTester {
    boolean test(String title);
}

TitleTester blank = String::isEmpty;       // t -> t.isEmpty()
blank.test("");                            // true

isEmpty isn't static: you call it on a specific String. String::isEmpty means call isEmpty on whatever String arrives. A class name on the left doesn't mean the method is static.

With several parameters:

interface PrefixCheck {
    boolean check(String title, String prefix);
}

PrefixCheck pc = String::startsWith;       // (t, p) -> t.startsWith(p)
pc.check("Narcos", "Nar");                 // true
  • The first parameter is the object the method runs on.
  • The other parameters are passed, in order, as arguments.

Shape 4 โ€” A constructor

record Episode(String name) { }

interface EpisodeMaker {
    Episode make(String name);
}

EpisodeMaker maker = Episode::new;         // name -> new Episode(name)
Episode pilot = maker.make("Pilot");       // Episode[name=Pilot]

::new points at a constructor. There are no parentheses: Java matches the interface's parameters to a constructor, here the one taking a String. Each call to make() creates a new object.

The four shapes side by side

Math::round           // p -> Math.round(p)               1 ยท static method
title::startsWith     // s -> title.startsWith(s)         2 ยท method on an object
String::isEmpty       // t -> t.isEmpty()                 3 ยท method on the parameter
String::startsWith    // (t, p) -> t.startsWith(p)        3 ยท method on the parameter
Episode::new          // n -> new Episode(n)              4 ยท constructor

How to read a reference:

Left side Method Shape
a class static 1: the parameters become the arguments
a variable any instance method 2: it always runs on that object
a class instance method 3: the first parameter becomes the object
a class new 4: a constructor

When unsure, rewrite the reference as a lambda in your head: the parameter order becomes obvious, and so does whether the counts line up.

The lab uses three shapes at once to fill, filter and print a movie catalog.

๐Ÿ’ป Code: Java17_Part_8_Functional_Programming on GitHub

โ† The :: shortcut ยท Next: the lab โ†’