Virtual Extension Methods(or Defender Methods) in Java 8

As part of the JSR-335 (Project Lambda) which adds closure support to Java language, there were quite a few changes in the language to support the use of closures in the existing Java APIs (Collection APIs to a large extent). One such change is the introduction of Virtual Extension Methods.

also read:

We all are aware of the fact that the interfaces don’t contain any implementation for the methods. To provide support for new APIs which support the use of closures and also which can run on Multi core platforms there has to be some way to add these APIs to existing classes. For example, methods like forEach, map, reduce, filter which act on a collection can be added to the Collection class directly or create a new interface and let all the collection API implement them or leave it to the user of the API to implement the new interface. The first 2 approaches would lead to breaking lots of existing code because of the lack of implementation of these new methods in the interface. The last approach is possible, but it doesn’t enhance the collection API out of the box.

The team which handles JSR-335 thought of a way to add default implementation to the interfaces, which gives an option for the implementor to override the method or to leave it as is. This way new APIs can be added to the Collection class without breaking the existing code and yet provide the full support of the closures to the existing code. One can read in depth about Virtual Extension Methods here.

Lets see an example of a virtual extension method:

 
interface TestInterface{
  public void testMe();
  
  public void aDefaulter() default{
    System.out.println("Default from interface");
  }
}

Using the “default” keyword we can add new methods to the existing interface and allowing the implementing classes to use this default implementation if they don’t override. Something like:

 
public class DefenderMethods{
  public static void main(String[] args){
    InterfaceImplementer imp = new InterfaceImplementer();
    imp.testMe();
    imp.aDefaulter();
  }
}
class InterfaceImplementer implements TestInterface{
  public void testMe(){
    System.out.println("Hello World!");
  }
}

The output for above program would be:

~/javaP/java8$ javac DefenderMethods.java 
~/javaP/java8$ java DefenderMethods 
Hello World!
Default from interface

Moving further, we can override the aDefaulter method in its implementing class, something like

 
class InterfaceImplementer implements TestInterface{
  public void testMe(){
    System.out.println("Hello World!");
  }
  
  public void aDefaulter(){
    System.out.println("Defautler overridden from class");
  }
}

for which the output will be:

~/javaP/java8$ javac DefenderMethods.java 
~/javaP/java8$ java DefenderMethods 
Hello World!
Defautler overridden from class

The bytecode generated for the DefenderMethods class still uses invokevirtual opcode for invoking the default method, which indicates its treated like any other usual interface method in its invocation.

There’s lot more to this concept like overriding rules, method invocation rules which I would like to cover in subsequent posts. And also sample code from the JDK 8 which uses this feature.

Comments

comments

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Comments

  1. Oliver says:

    Hi Mohamed ,

    interesting post. This way traits could be mimicked to some extend, no? Unhappily, I can’t get your code to compile with JDK8, even when I do this:

    javac -source 1.8 -target 1.8 TestInterface.java

    I get:

    C:ProgrammeJavajdk1.8.0bin>javac -target 1.8 TestInterface.java
    TestInterface.java:5: error: ‘}’ expected
    System.out.println(“Default from interface”);
    ^
    TestInterface.java:7: error: class, interface, or enum expected
    }

    Any hint appreciated :-)

    Cheers, Oliver

    • Traits are much more than defender methods. And traits can be mixed in at the instance level. I would have to spend sometime to write about how traits and defender methods differ.
      For compiling you need to download the JDK from here: http://jdk8.java.net/lambda/ i.e you should have the JDK which supports lambda expressions.

    • Traits are much more than defender methods. And traits can be mixed in
      at the instance level. I would have to spend sometime to write about how
      traits and defender methods differ.
      For compiling you need to download the JDK from here: http://jdk8.java.net/lambda/ i.e you should have the JDK which supports lambda expressions.

  2. Martin Skarsaune says:

    Hi

    Which build of javac did you use in order to compile the code?

    Thanks

    Martin

Trackbacks

  1. [...] is a list of method resolution approach for virtual extension methods explained here. One of the interesting ones is when a class implements multiple interfaces and say 2 of the [...]

  2. [...] wrote a bit about Virtual extension methods here and here. I thought of going over this implementation in the JDK, so that it will give us an idea [...]

  3. [...] announced here that the Iteration 1 of Lambda Libraries is complete which includes support for defender methods, enhancement of the collection apis among other [...]

  4. [...] Continuing with our exploration of JSR-335 lets look at some of the enhancements to the collections API as part of the Project Lambda effort. A new feature in the language and not supported by the existing API is just not what the programmers would want. And this is what Brian Goetz and his team working on JSR-335 realized. It was not an easy task of enhancing the existing API without breaking uncountable lines of code. That was a challenge which they took up and managed to get around this by introducing the concept of defender methods. [...]

  5. [...] interfaces. These interfaces don’t contain any implementations. (This is going to change with Defender Methods in Java 8). Lot of other languages support interface like constructs but with greater power. And [...]

  6. [...] Introduction to Virtual Extension Methods in Java 8 . [...]

  7. [...] Virtual Extension Methods(or Defender Methods) in Java 8 [...]

  8. [...] Lambdas Expressions dans le JDK8 qui m’a permis de comprendre que Java 8 avec les lambdas et les Virtual Extension methods (qui introduisent de l’héritage multiple en Java) allaient amener une rupture aussi importante [...]

Speak Your Mind

*