If, let's say, we've added the new method to the interface List, then we could simply implement it where it's needed (ArrayList, LinkedList ,etc.) event with no default method implementation?
How do you do that when you do not control all implementations of List
? You (meaning the Java Gods) can add it in the JDK, but how about all the implementations in other people's code? Those would not compile anymore. And if someone tried to call one of the new methods on their implementation (from a previously compiled JAR file) they'd get a nasty MethodNotFoundError
at runtime.
Backwards compatibility means that existing code can work without modifications. In this case, they aim for source compatibility, which means you can compile the same source code without changes against the new Java version. The other thing is binary compatibility, which means that old compiled classes continue to work (which Java is famous for).
Source compatibility has been broken from time to time (for example the JDBC API is notorious for getting new interface methods all the time), but not in such a central class such as List
(the JDBC changes only affected database driver vendors, not application code).
So without default methods, no new methods could have been added to the List
interface. It would have needed to be an additional EnhancedList
or ListV8
(that all JDK lists would have implemented but all using code would have needed to refactor to make use of).