4

1.InterfaceOne is one interface having two methods ,my question i how to override that 2 methods using Lambda expression?

interface InOne{

    void m1();
    void m2();
}
public class LambdaExpForTwomethodsInInterface {

    public static void main(String[] args) {

        //For One method overriding
        InOne one=()->{
            System.out.println("InOne m1");
        };
        one.m1();
    }
}

2.If there are 5 methods in interface,but i want to override only one method,is there any way to that using Lambda exp?

mae
  • 117
  • 2
  • 12

2 Answers2

4

is there any way to that using Lambda exp?

No, they are meant to be referencing only FunctionalInterfaces.

how to override that 2 methods using Lambda expression?

Though not possible using a lambda expression, you can still use an anonymous class to instantiate them:

InOne one = new InOne() {
    @Override
    public void m1() {

    }

    @Override
    public void m2() {

    }
};
Naman
  • 27,789
  • 26
  • 218
  • 353
  • You mean ,Lambda deal only with funtional interface? – mae Feb 08 '19 at 12:01
  • @mae yup, precisely... Would refer you to read further details around https://stackoverflow.com/questions/23342499/why-functional-interfaces-in-java-8-have-one-abstract-method – Naman Feb 08 '19 at 12:02
0
interface InOne {
    default void m1() {}
    default void m2() {}
}

Implement

InOne one = new InOne() {
    @Override
    public void m1() {
        System.out.println("InOne m1");
    }
};

one.m1();  // InOue m1
one.m2();  // <nothing>

Implement using Lambda

@FunctionalInterface
interface InOneM1 {
    void m1();
}

@FunctionalInterface
interface InOneM2 {
    void m2();
}

InOneM1 oneM1 = () -> System.out.println("InOne m1");
InOneM2 oneM2 = () -> System.out.println("InOne m2");

oneM1.m1();
oneM2.m2();
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
  • If it is dealing only with Funtional interfaces ,then how it is dealing reducing code and giving much importance.I mean generally ,we have more then one methods in interfaces of our projects right..! – mae Feb 08 '19 at 12:05
  • Right. Lambda works only with **Functional Interface** – Oleg Cherednik Feb 08 '19 at 12:08
  • @oleg.cherednik `` rather shall mean `void`... by the way, there is another combination as well one of them being `default` and another being `abstract` to term the interface as `FunctionalInterface`... but that should be considered while approaching towards designing them. – Naman Feb 08 '19 at 12:09
  • @mae not every interface is supposed to be represented using lambdas.. you can still have interfaces which are not `FunctionalInterface`.. but in order to make use of them, one can design the interfaces and their hierarchy as such. – Naman Feb 08 '19 at 12:10