Functional interfaces

Hey everyone, I am currently working my way through the lambda expression and functional interfaces in part 3 of the Java course.

After some googling I realised that List.of() is a factory method but I am still unsure what this means. Does it instantiate a List object? If so how is this possible since List is an interface and not a class. My understanding was that interfaces could not be instantiated. And if it is not instantiating a List object, what class does this object belong to?

My second question also relates to this.
Consumer print = item → System.out.println(item);

Would someone be so kind as to explain what is being instantiated here? I am unsure which class this object belongs to since Consumer is an interface. I feel like I am missing something very important here. I am not sure whether there is a specific section that I should re-watch perhaps. Any clarification would be greatly appreciated :slightly_smiling_face:

Yes, it instantiates a new List object. Specifically, it instantiates an unmodifiable list (meaning the contents of the list itself cannot be changed even if the elements themselves are mutable). This is not just trying to call new List(...), but it is creating an instance of some unspecified class that implements the List interface. The unspecified class is considered an implementation detail.

The item -> System.out.println(item) bit there is a lambda expression. The code is creating a function and storing it in a variable print which has the type Consumer. Technically Consumer is a generic interface so we should specify a type argument, but if not specified it is basically Consumer<Object>.

You should probably re-watch the whole “Lambda Expressions and Functional Interfaces” section of Part 3 (~45 minutes long), but in particular you may be interested in 4- Lambda Expressions | Code with Mosh and 8- The Consumer Interface | Code with Mosh.

1 Like