DefaultMethods
From APIDesign
(→By-Passing Your Interface) |
|||
Line 16: | Line 16: | ||
</source> | </source> | ||
- | [[I]] thought I did everything correctly, as all the methods of the {{JDK|java/util|List}} interface are properly overwritten. But of course, the problem appeared with [[DefaultMethods]]. | + | [[I]] thought I did everything correctly, as all the methods of the {{JDK|java/util|List}} interface are properly overwritten. But of course, the problem appeared with [[DefaultMethods]]. If you write [http://hg.netbeans.org/html4j/file/0b81a0bcf46f/json/src/test/java/net/java/html/json/MapModelTest.java#l305 this code]: |
+ | |||
+ | <source lang="java"> | ||
+ | People p = new People(); | ||
+ | List<String> names = p.getNicknames(); | ||
+ | Collections.sort(names); | ||
+ | </source> | ||
+ | |||
+ | it works properly on [[JDK]]7, but it gets broken on [[JDK8]]: the notification change isn't delivered! |
Revision as of 07:59, 24 September 2016
DefaultMethods is a new feature in JDK8 which breaks the clear separation between Java interface (only specifies a contract) and class (provides some implementation). Many members of the Java community were crying for having a way to add methods into interface in a backward compatible way for ages. Of course, as usual inJava, only when the JDK team felt the need itself (because of adding a lot of new methods into Collection & co. classes), it listen to the general request.
On the other hand, there were people claiming that DefaultMethods are bad - that an interface should be a code-less specification and the change will have consequences. Here is one.
By-Passing Your Interface
When I was implementing Html4Java API, I had to create an observable list - so I did it and created JSONList. I've carefully overwritten each public method that modified the list state and called a change notification handler. What can be the problem?
@Override public boolean add(T e) { boolean ret = super.add(e); notifyChange(); return ret; }
I thought I did everything correctly, as all the methods of the List interface are properly overwritten. But of course, the problem appeared with DefaultMethods. If you write this code:
People p = new People(); List<String> names = p.getNicknames(); Collections.sort(names);
it works properly on JDK7, but it gets broken on JDK8: the notification change isn't delivered!