Java - Instance Method References Supertype

Introduction

The keyword super is used as a qualifier to invoke the overridden method in a class or an interface.

The keyword is available only in an instance context.

Syntax

The syntax for a method reference referring to the instance method in the supertype.

TypeName.super::instanceMethod

Example

Priced interface contains a default method that returns 1.0.

Product class implements the Priced interface and overrides the toString() method and the getPrice() method of the Priced interface.

The following method references with a bound receiver are illustrated.

method reference refer to
this::toString refers to the toString() method of the Product class.
Product.super::toString refers to the toString() method of the Object class, which is the superclass of the Product class.
this::getPrice refers to the getPrice() method of the Product class.
Priced.super::getPrice refers to the getPrice() method of the Priced interface, which is the superinterface of the Product class.

Demo

import java.util.function.Supplier;

interface Priced {
  default double getPrice() {
    return 1.0;/*from  ww w .  ja v  a 2s . co m*/
  }
}

class Product implements Priced {
  private String name = "Unknown";
  private double price = 0.0;

  public Product() {
    System.out.println("Constructor Product() called.");
  }

  public Product(String name) {
    this.name = name;
    System.out.println("Constructor Product(String) called.");
  }

  public Product(String name, double price) {
    this.name = name;
    this.price = price;
    System.out.println("Constructor Product(String, double) called.");
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void setPrice(double price) {
    this.price = price;
  }

  @Override
  public double getPrice() {
    return price;
  }

  @Override
  public String toString() {
    return "name = " + getName() + ", price = " + getPrice();
  }

  public void test() {
    // Uses the Product.toString() method
    Supplier<String> s1 = this::toString;

    // Uses Object.toString() method
    Supplier<String> s2 = Product.super::toString;

    // Uses Product.getPrice() method
    Supplier<Double> s3 = this::getPrice;

    // Uses Priced.getPrice() method
    Supplier<Double> s4 = Priced.super::getPrice;

    // Uses all method references and prints the results
    System.out.println("this::toString: " + s1.get());
    System.out.println("Product.super::toString: " + s2.get());
    System.out.println("this::getPrice: " + s3.get());
    System.out.println("Priced.super::getPrice: " + s4.get());
  }
}
public class Main {
  public static void main(String[] args) {
    Product apple = new Product("Apple", 0.75);
    apple.test();
  }
}

Result

Related Topic