CIS-260 Home http://www.c-jump.com/bcc/
More about
Interface
Inheritance
Composition
|
|
A UML example of the interface, inheritance, and composition:
An interface is similar to a class, except...
interface has no attributes
interface has only method declarations (headers) without implementation.
We already know that...
...a class in Java extends from abstract super class.
Similarly,
a class in Java implements an interface.
OO programming languages provide good tools to develop reusable code.
Interfaces can only be used with inheritance relationship.
Interfaces cannot be used with a composition relationship.
Java does not support multiple inheritance of classes...
...Java supports multiple inheritance of interfaces.
|
|
Any class that implements an interface must also implement concrete code for each method listed in the interface.
If class fails to implement a method declared in the interface, the class will not compile...
...because in Java the interface contract must be enforced.
Multiple inheritance can be very useful in some cases.
Java uses multiple inheritance in a very limited way, only with interfaces.
Interfaces come with some serious limitations:
Methods cannot have default implementations, thus forcing the programmer to implement each method again and again in each class that implements the interface.
This often forces programmers to repeat code over and over again.
For example,
You found a suitable interface in existing Java software: it already has 10 functions.
Of these 10 functions you may need only 3. However, you are forced to implement all of the functions simply because Java forces you to do so.
Solution 1: keep the interfaces small.
Impractical solution 2: hope that one day Java will have default method implementation...