Interfaces
- An
interface
is an abstract class where all the methods are abstract (and public) and
they define the interface
(i.e. the methods) to all the classes in the hierarchy.
- In this type of hierarchy, the interface is higher in the hierarchy while
the implementation details are lower in the hierarchy.
- So we can code a shape hierarchy such that all shapes must have a draw()
method, while the code for drawing shape1 is in the shape1 draw()
method and the code for drawing shape2 is in the shape2 draw() method.
- An interface is used in place of multiple inheritance. Since the class
that implements the interface must write the code for each method, there is
no ambiguity as to which method will be called.
- Interfaces allow you to design a hierarchy that can be extended to
classes that haven't been created yet.
- For instance, you may have noticed that Java calls many methods for you.
This is because it is calling "known" methods - i.e. the signature
for the method is known.
- One way to allow this in
a class hierarchy is to define the known methods as an interface. Then
any class that implements the interface, must implement
the methods in the interface.
- Multi-threading and event handling in Java both use interfaces, as does Android.