Lambda Methods and Anonymous Classes
Yes. We can have default methods within an interface and also allow that interface to be a functional interface but we cannot use them within lambda expressions. However, we an use the lambda expression within our default methods!
Can we use default methods in functional interfaces?
interface Op { public abstract int apply(int a, int b); } .... Op add = ((a, b) -> a + b);
Give an example of an implemented lamdba method
It is an inner class without a name and for which only a single object is created. An anonymous class has the following properties: Only one instance of an anonymous class exists. It is typically declared within a method. An anonymous class is immediately constructed and an instance is returned to the caller.
What are anonymous classes?
An interface
What do we need in order to create anonymous classes?
A functional interface is an interface that has just one abstract method, and thus represents a single function contract.
What is a functional interface?
Lambda methods require an interface that declares only one method. After an interface has been defined and only contains one ABSTRACT method, it can adhere to the following usage of lambda's: (arg1[, arg2...]) -> functionBody
What is required in order to implement a lambda method?
The syntax is: new Type() { [fields] [methods] }
What is the syntax for writing an anonymous class?
If it is necessary for a lambda expression to refer to itself (via this), then a method reference or anonymous class should be used instead.
When should we use method references / anonymous classes over lambda methods?
A Functional Interface serves as a data type for Lambda expressions.
Why do lambda expressions require a functional interface?
An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class. Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming.
Why would we use anonymous classes?