To update the existing Collections library for lamba (proposed for Java 8), another new feature proposed for Java 8 is Virtual Extension Methods.
One of the problems of using interfaces, is that you are unable to add new methods to interfaces without potentially causing problems for existing libraries that were already developed/compiled against the original interface definition. So unless you can rebuild those libraries against your updated Interface definition, you’re stuck! This is where Virtual Extension Methods will come to the rescue.
The Scenario
An interface was created by Bob.
public interface DefenderMethod{
void method1();
}
Alice creates class DefenderMethodImpl that implements DefenderMethod
Now Bob wants to add a new methods to the interface, this might cause problems for Alice if she pulls in Bobs latest interfaces updates, she may get runtime errors if her class runs against against the updated interfaces, or if she re-compiles, she will get compilation errors which need to be resolved.
This is where virtual extension methods will be very useful, for methods on the interface, we can specify a default implementation for the method, this means we maintain binary and source compatibility for existing classes that were compiled against this interface. So now Bob can add new virtual extension methods to his interface without worrying about causing problems for Alice, thus preserving both binary (Alice doesn’t need to recompile) and source compatibility (Alice doesn’t need to change her code).
To implement a virtual extension method, you add “default” after the method signature, followed by the actual static method that be used as the default implementation.
public interface DefenderMethod{
void method1();
int method2(int val) default {
System.out.println("default method invoked called with args "+val);
return val+4;
}
}
If the interface (InterfaceFoo) is extended by another interface (InterfaceBar) , the default method of the extended interface (InterfaceBar) is preffered. If implementers of the class have defined the methods, these will be used in preference to the default method implementation.
How does this compare to C# Extension Method?
C# Extension Methods uses a compiler trick, the compiler when it sees you are calling an extension method (which is basically a static method whose first argument is the same type as the instance), even though the source code you write, looks like you are calling an instance method, the byte-code that is generated for this is actually a call to the static method, because this is not implemented as a VM feature, this is brittle compared to the virtual extension methods proposed for Java. The other difference is C# extension methods are only available in the site where the the extension method is imported, java extension methods will be available to all implementers of the interface.
