Virtual Extension Methods in upcoming Java 8 release

前端 未结 5 735
既然无缘
既然无缘 2020-12-31 10:23

When I see code snippets like

  interface A {
      void a();
      void b() default { System.out.println(\"b\"); };
      void c() final { System.out.printl         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 10:33

    It is planned that Java 8 will contain some form of lambda and closure support, which would be a big step in modernizing the Java language. The problem is that existing libraries based on interfaces, like the collection framework, won't be able to directly use these new features. It is not possible to add a method to an interface without breaking existing implementations, they would simple no longer compile.

    Having lambdas, but not being able to easily use them with standard collections, would be a huge letdown for java developers. To integrate lambdas into the standard collections, methods like forEach, map, or filter would be highly desirable.

    The solution to this problem is to add another feature, extension methods, which define a default implementation of a method in a interface. Existing subclasses would use the default method, but it is also possible to override the method with a specialized and possible better implementation.

    More information about the extension method proposal can be found at Java Enhancement Proposal 126.

提交回复
热议问题