Skip to content

Reference To Instance Method Of An Object (Method References)

In this lesson, you will learn about the second kind of method reference, "a reference to an instance method of an object". You will be introduced to complex object method references with example snippets and explanations.

Gopi Gorantala
Gopi Gorantala
2 min read

Table of Contents

What is a reference to the instance method of an object mean?

A static method reference refers to the static method for a class. We can use a method reference to call the static methods directly.

Syntax

The syntax for referencing a static method is as follows.

ObjectName::staticMethodName

Example

Let us write a simple example that contains four files

  1. Book - a POJO class with getters and setters. You can replace the class with Java record , also.
  2. BookRepository - for database transactions.
  3. BookRepositoryImpl - An implementation class that injects fake data.
  4. ReferenceToInstance - This is where the actual magic happens.

Code

public class Book {
  private final String title;
  private final String author;
  private final int year;
  private final int copiesSoldInMillions;
  private final double rating;
  private final double costInEuros;

  public Book(
      String title,
      String author,
      int year,
      int copiesSoldInMillions,
      double rating,
      double costInEuros) {
    this.title = title;
    this.author = author;
    this.year = year;
    this.copiesSoldInMillions = copiesSoldInMillions;
    this.rating = rating;
    this.costInEuros = costInEuros;
  }

  public Double getCostInEuros() {
    return costInEuros;
  }

  public double getRating() {
    return rating;
  }

  public String getTitle() {
    return title;
  }

  @Override
  public String toString() {
    return "commons.Book{ title="
        + title
        + ", author="
        + author
        + ", copiesSoldInMillions="
        + copiesSoldInMillions
        + ", costInEuros="
        + costInEuros
        + "}";
  }
}
import java.util.List;

public interface BookRepository {
  List<Book> getAllBooks();
}
import java.util.Arrays;
import java.util.List;

public class BookRepositoryImpl implements BookRepository {

  @Override
  public List<Book> getAllBooks() {
    return Arrays.asList(
        new Book("Don Quixote", "Miguel de Cervantes", 1605, 500, 3.9, 9.99),
        new Book("A Tale of Two Cities", "Charles Dickens", 1859, 200, 3.9, 10.0),
        new Book("The Lord of the Rings", "J.R.R. Tolkien", 2001, 150, 4.0, 12.50),
        new Book("The Little Prince", "Antoine de Saint-Exupery", 2016, 142, 4.4, 5.0),
        new Book("The Dream of the Red Chamber", "Cao Xueqin", 1791, 100, 4.2, 10.0));
  }
}
import java.util.List;

public class ReferenceToInstance {
  public static void main(String[] args) {
    BookRepositoryImpl bookRepositoryImpl = new BookRepositoryImpl();

    // Inflate fake books
    List<Book> books = bookRepositoryImpl.getAllBooks();

    // Reference to instance
    ReferenceToInstance referenceToInstance = new ReferenceToInstance();

    System.out.println("SORT BASED ON PRICE");
    books.sort(referenceToInstance::compareByCost);
    books.stream()
        .map(book -> book.getTitle() + " -> " + book.getCostInEuros())
        .forEach(System.out::println);

    System.out.println("------");

    System.out.println("SORT BASED ON TITLES: ");
    books.sort(referenceToInstance::compareByTitle);
    books.stream()
        .map(book -> book.getTitle() + " -> " + book.getRating())
        .forEach(System.out::println);
  }

  public int compareByTitle(Book first, Book second) {
    return first.getTitle().compareTo(second.getTitle());
  }

  public int compareByCost(Book first, Book second) {
    return first.getCostInEuros().compareTo(second.getCostInEuros());
  }
}

Explanation

Book, BookRepository, and BookRepositoryImpl files are self-explanatory. So let's see whats happening in ReferenceToStaticMethod class.

Lines 28 to 30 contain a static method compareByTitle(), which sorts the list of Book objects based on the title.

Lines 32 to 34 contain a static method compareByCost(), which sorts the list of Book objects based on costInEuros per each book.

In line 5, we created an instance of BookRepositoryImpl class. We use this reference instance to call .getAllBooks() the method in line 8 to load the fake data into a collection of objects List<Book>.

We created an instance of ReferenceToInstance class on line 11.

In lines 14 and 22, we are calling the non-static methods we declared inside the class to sort the list of Book objects.

The following explanation is the same for code snippet lines from "15 to 17" and "23 to 25".

On line 15, we chained the collection of book objects stored in books variable with .stream(), which converts all the collections of Book objects into a Stream of Book objects.

Line 16 contains an intermediate stream operation .map(...) forms stream of Book objects based on the parameters that are included inside the method, in this case title and costInEuros.

Line 17 contains a simple .forEach a terminal operation for printing elements on the console.

Java

Gopi Gorantala Twitter

Gopi is a highly experienced Full Stack developer with a deep understanding of Java, Microservices, and React. He worked in India & Europe for startups, the EU government, and tech giants.

Comments


Related Posts

Members Public

How To Write Lambda Expressions

This lesson introduces the basic lambda expression structure with tips to write efficient code.

Members Public

What Are Lambda Expressions?

This is an introductory lesson on lambda expressions. You will learn about the lambda operator, expression, syntaxes and more!

Members Public

Power Of Two (Exercise Problem)

This is an exercise problem for your practice. Try to come up with an approach and solve it by yourself. Good Luck!