Why do I need a functional Interface to work with lambdas?

前端 未结 6 2160
故里飘歌
故里飘歌 2020-11-27 15:09

I think this question is already somewhere out there, but I wasn\'t able to find it.

I don\'t understand, why it\'s necessary to have a functional interface to work

6条回答
  •  悲哀的现实
    2020-11-27 15:41

    You seem to be looking for anonymous classes. The following code works:

    public class Test {
    
        public static void main(String...args) {
            TestInterface i = new TestInterface() {
                public void hans() {
                    System.out.println("Hans");
                }
                public void hans(String a) {
                    System.out.println(a);
                }
            };
    
            i.hans();
            i.hans("Hello");
        }
    }
    
    public interface TestInterface {
        public void hans();
        public void hans(String a);
    }
    

    Lambda expressions are (mostly) a shorter way to write anonymous classes with only one method. (Likewise, anonymous classes are shorthand for inner classes that you only use in one place)

提交回复
热议问题