Java Magazine, September/October 2016
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2016 51 new to java and now adding the newer Java 8 features I did this on purpose because understanding the justification for the combination of features as they are today is possible only in light of this history If the Java team were to design Java from scratch now and if breaking backward compatibility were not a problem they would not design it in the same way The Java language is however not foremost a theoretical exercise but a system for practical use And in the real world you must find ways to evolve and extend your language without breaking everything that has been done before Default methods and static methods in interfaces are two mechanisms that made progress possible in Java 8 Evolving Interfaces One problem in developing Java 8 was how to evolve interfaces Java 8 added lambdas and several other features to the Java language that made it desirable to adapt some of the existing interfaces in the Java library But how do you evolve an interface without breaking all the existing code that uses this interface Imagine you have an interface MagicWand in your existing library public interface MagicWand void doMagic This interface has already been used and implemented by many classes in many projects But you now come up with some really great new functionality and you would like to add a really useful new method public interface MagicWand void doMagic void doAdvancedMagic If you do that then all classes that previously implemented this interface break because they are required to provide an implementation for this new method So at first glance it seems you are stuck either you break existing user code which you dont want to do or youre doomed to stick with your old libraries without a chance to improve them easily In reality there are some other approaches that you could try such as extending interfaces in subinterfaces but these have their own problems which I do not discuss here Java 8 came up with a clever trick to get the best of both worlds the ability to add to existing interfaces without breaking existing code This is done using default methods and static methods which I discuss next Default Methods Default methods are methods in interfaces that have a method body the default implementation They are defined by using the default modifier at the beginning of the method signature and they have a full method body public interface MagicWand void doMagic default void doAdvancedMagic some code here Classes that implement this interface now have the chance to provide their own implementation for this method by overriding it or they can completely ignore this method
You must have JavaScript enabled to view digital editions.