Java Reference
In-Depth Information
implement the method setRelativeSize. Adding a new method to an interface is binary
compatible ; this means existing class file implementations will still run without the
implementation of the new method, if there's no attempt to recompile them. In this case the
game will still run (unless it's recompiled) despite adding the method setRelativeSize to the
Resizable interface. Nonetheless, the user could modify the method Utils.paint in his game to
use the method setRelativeSize because the paint method expects a list of Resizable objects as
argument. If an Ellipse object is passed, an error will be thrown at run-time because the
setRelative-Size method isn't implemented:
Exception in thread "main" java.lang.AbstractMethodError:
lambdasinaction.chap9.Ellipse.setRelativeSize(II)V
Second, if the user tries to rebuild his entire application (including Ellipse), he'll get the
following compile error:
lambdasinaction/chap9/Ellipse.java:6: error: Ellipse is not abstract and does not override
abstract method setRelativeSize(int,int) in Resizable
Consequently, updating a published API creates backward incompatibilities. This is why
evolving existing APIs, such as the official Java Collections API, causes problems for users of the
APIs. There are alternatives to evolving an API, but they're poor choices. For example, you could
create a separate version of your API and maintain both the old and the new versions, but this is
inconvenient for several reasons. First, it's more complex for you to maintain as a library
designer. Second, your users may have to use both versions of your API in the same codebase,
which impacts memory space and loading time because more class files are required for their
projects.
This is where default methods come to the rescue. They let library designers evolve APIs without
breaking existing code because classes implementing an updated interface automatically inherit
a default implementation. [ 1 ]
1 See https://blogs.oracle.com/darcy/entry/kinds_of_compatibility .
Different types of compatibilities: binary, source, and behavioral
There are three main kinds of compatibility when introducing a change to a Java program:
binary, source, and behavioral compatibilities. 1 You saw that adding a method to an interface is
binary compatible but results in a compiler error if the class implementing the interface is
Search WWH ::




Custom Search