Java Reference
In-Depth Information
ference between an interface and a class is that a class can maintain state information, but
an interface cannot. Furthermore, it is still not possible to create an instance of an inter-
face by itself. It must be implemented by a class. Therefore, even though, beginning with
JDK 8, an interface can define default methods, the interface must still be implemented by
a class if an instance is to be created.
One last point: As a general rule, default methods constitute a special-purpose feature.
Interfaces that you create will still be used primarily to specify what and not how. However,
the inclusion of the default method gives you added flexibility.
Default Method Fundamentals
An interface default method is defined similar to the way a method is defined by a class .
The primary difference is that the declaration is preceded by the keyword default . For ex-
ample, consider this simple interface:
MyIF declares two methods. The first, getUserID( ) , is a standard interface method de-
claration. It defines no implementation whatsoever. The second method is getAdminID( ) ,
and it does include a default implementation. In this case, it simply returns 1. Pay special
attention to the way getAdminID( ) is declared. Its declaration is preceded by the default
modifier. This syntax can be generalized. To define a default method, precede its declara-
tion with default .
Because getAdminID( ) includes a default implementation, it is not necessary for an im-
plementing class to override it. In other words, if an implementing class does not provide
its own implementation, the default is used. For example, the MyIFImp class shown next
is perfectly valid:
Search WWH ::




Custom Search