Virtual Extension Methods in upcoming Java 8 release

3.8k views Asked by At

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?

5

There are 5 answers

0
deadalnix On BEST ANSWER

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.

7
andrew On

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.

1
Tom Anderson On

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.

2
Tassos Bassoukos On

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.

1
Jörn Horstmann On

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.