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.
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".