Home > Java > javaTutorial > body text

Confusion Around Method Referencing

Patricia Arquette
Release: 2024-09-23 06:21:14
Original
481 people have browsed it

Confusion Around Method Referencing

Method references in Java provide a way to refer to methodsor constructorswithout invoking them explicitly. They can be thought of as a shorthand for writing simple lambda expressions.

Majorly method referencing can either be static or related to an instance:

Integer::sum;
System.out::println;
Copy after login

These are examples of static method references (also known as bound referencing).

However, consider this:

String::concat
Copy after login

Here, concatis not a static method, so how is this working? This is an example of unbound referencing. The compiler understands that this is an instance method reference based on how our code is written. This makes it possible to simplify method calls like this.

The way we write our code determines these types of references (especially unbound ones). Taking concatas an example:

((a, b) -> a + b, "Hello", "World");
// ----------------Is same as -------------
((a, b) -> a.concat(b), "Hello", "World"); // This one could be replaced by mehod referencing

// ----------------Alternative-------------

(String::concat, "Hello", "World");

/* The use of 'a' as the first parameter and calling `concat `of 'a' itself 
gives the compiler an idea of how it should decode `String::concat`*/
Copy after login

So, instead of writing out a full lambda, we can simplify with a method reference.

Keep Learning ?

The above is the detailed content of Confusion Around Method Referencing. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template