Subclass Method Uses Lambda Expression to Implement Abstract Class Method In Java


Create a Java program to demonstrate method overriding with a subclass that overrides a method from an abstract class and uses a lambda expression to implement the method

The use of a lambda expression within a method in the context of method overriding in a subclass. Here's an explanation of the code:

  • MethodOverridingWithLambdaDemo is the main class containing the main method. It creates an instance of the Subclass and a lambda expression of a functional interface (MyFunctionalInterface).
  • MyFunctionalInterface is a functional interface with a single abstract method named myMethod.
  • AbstractClass is an abstract class that has an abstract method doSomething that takes an instance of MyFunctionalInterface.
  • Subclass is a concrete subclass of AbstractClass. It overrides the doSomething method, prints a message "Inside Subclass," and then calls the myMethod method of the functional interface provided as an argument.

In the main method:

  • An instance of Subclass named subObj is created.
  • A lambda expression myLambda is defined for the MyFunctionalInterface. This lambda expression prints "Lambda expression called!" when its myMethod is invoked.
  • The doSomething method of subObj is called, passing the lambda expression myLambda as an argument.

Source Code

public class MethodOverridingWithLambdaDemo
{
    public static void main(String[] args)
	{
        Subclass subObj = new Subclass();
 
        MyFunctionalInterface myLambda = () -> {
            System.out.println("Lambda expression called!");
        };
 
        subObj.doSomething(myLambda);
    }
}
 
@FunctionalInterface
interface MyFunctionalInterface
{
    void myMethod();
}
 
abstract class AbstractClass
{
    abstract void doSomething(MyFunctionalInterface func);
}
 
class Subclass extends AbstractClass
{
    @Override
    void doSomething(MyFunctionalInterface func)
	{
        System.out.println("Inside Subclass");
        func.myMethod();
    }
}

Output

Inside Subclass
Lambda expression called!