Virtual Extension Methods in upcoming Java 8 release

牧云@^-^@ 提交于 2019-12-30 03:05:21

问题


When I see code snippets like

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

I have one question. Haven't we already got enough sh*t in Java? Why one might need this?


回答1:


I suggest you to look at this conference : http://medianetwork.oracle.com/media/show/16999

This explain everything. The most interesting thing to do is to allow an interface to evolve without rewritting your whole codebase. This is key to allow a big codebase to evolve and not become more and more crippled.




回答2:


We need this because it will make the Scala guys absolutely furious. They already have rather similar functionality in the shape of 'traits', so now they'll have to make those work together with these.

Pissing off Scala guys is literally the highest priority in Java language development.




回答3:


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.




回答4:


This is great because it allows you, the API writer to post-hoc extend interfaces without causing NoSuchMethodErrors. It also You provide default implementations for methods in V2 for classes compiled against V1; code works like a charm. This also allows you to override the default implementation in classes compiled against V2 as usual, and makes numbered interafces redundant. I consider it also superior than use-site extension methods.




回答5:


I believe that "extension methods" concept is no more than just the last chance to hack/fix poorly designed APIs which have been exposed to "external world". Just syntactic sugar.



来源:https://stackoverflow.com/questions/9025230/virtual-extension-methods-in-upcoming-java-8-release

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!