0

I am trying to understand Supplier interface. I understand that it can return an object if we invoke its get() method. However, in the following example:

public class SupplierExample {

    public static void main(String[] args) {
        Supplier<String> s = new Supplier<String>() {
            public String get() {
                return "test";
            }
        };

        System.out.println(s.get());
    }
}

I am not able to understand how we can instantiate an object (s in above exaple) from an interface. Please advise.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sukh
  • 424
  • 5
  • 16
  • You instantiated an anonymous class that implements the Supplier interface. – bdkosher Feb 05 '20 at 14:46
  • 1
    Note that you can also use lambdas and method references to instantiate instances of interfaces like `Supplier`. An example: `Supplier s = () -> "test";`, pretty compact. – Zabuzard Feb 05 '20 at 14:47

1 Answers1

1

This snippet contains an anonymous class instance, which implements the Supplier<String> interface.

It implements the only method of that interface with:

public String get() {
    return "test";
}

which returns the String "test".

Therefore, s.get() returns the String "test".

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Eran, it means it is an anonymous inner class syntax where we have to write Interface name after new operator? – Sukh Feb 05 '20 at 15:43