In designing a program, how do I know when to use an interface or a class?Is there a basic rule to follow?
Java supports a limited form of multiple inheritance. You may only derive a class from a single superclass, but it may implement asmany interfaces as you want. An interface is in essence anabstract class with no implemented methods. It only defines thosemethods that must be implemented by a subclass.
Therefore multipleinheritance of implementation is not possible in Java, although itmay be simulated through aggregation and delegation. Interfacesserve many purposes in Java. You will see them used as a replacementfor function pointers, as a mechanism for storing constants thatneed to be shared by several related classes, and as abstract classesamong other things.
In general, you use an interface when eachsubclass would need to implement the methods differently. Interfacesdefine common behavior, but not the implementation of that behavior.This allows you to hide classes behind factory patterns that returnreferences to an interface. When a class actually needs to rely onimplemented functionality in a superclass, you will not implementthe superclass as an interface. Classes allow you to define protectedmethods 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 rulethat dictates when to use an interface or a class. The choicedepends on the problem you are trying to solve, the decompositionof functionality, and ultimately your design framework.