Question:
In designing a program, how do I know when to use an interface or a class?
Is there a basic rule to follow?
Answer:
Java supports a limited form of multiple inheritance. You may only
derive a class from a single superclass, but it may implement as
many interfaces as you want. An interface is in essence an
abstract class with no implemented methods. It only defines those
methods that must be implemented by a subclass.
Therefore multiple
inheritance of implementation is not possible in Java, although it
may be simulated through aggregation and delegation. Interfaces
serve many purposes in Java. You will see them used as a replacement
for function pointers, as a mechanism for storing constants that
need to be shared by several related classes, and as abstract classes
among other things.
In general, you use an interface when each
subclass would need to implement the methods differently. Interfaces
define common behavior, but not the implementation of that behavior.
This allows you to hide classes behind factory patterns that return
references to an interface. When a class actually needs to rely on
implemented functionality in a superclass, you will not implement
the superclass as an interface. Classes allow you to define protected
methods that may be accessed by subclasses but not external classes.
Interface methods are always public.
It would be a bit disingenuous to say that there is a general rule
that dictates when to use an interface or a class. The choice
depends on the problem you are trying to solve, the decomposition
of functionality, and ultimately your design framework.