Difference between extends and implements
- When a subclass extends a class, it allows the subclass to inherit (reuse) and override code defined in the supertype.
- When a class implements an interface, it allows an object created from the class to be used in any context that expects a value of the interface.
Thus if a variable has a type given by an interface, then any object from a class implementing that interface can be assigned to that variable. If a formal parameter's type is given by an interface, any object from a class implementing the interface can be used as an actual parameter in that slot. While we haven't seen an example here, we may also use a superclass in these ways. For example, a variable of type LaundryImpl can be assigned an object of type Pants or Tshirt.
Since extends is more powerful, why use implements? Java requires that a class may extend at most one other class. Extending multiple classes introduces a very difficult problem if, for example, the two classes that we are trying to extend both define an instance variable with the same name or a method with the same signature. How can our new class inherit both since they have the same name? Numerous languages have tried to define rules to deal with this, but none of the solutions has been good. Java avoids it by disallowing this multiple inheritance. So if we want a class to be a subtype of more than one other type, only one may be a class that we extend, the others must be interfaces that we implement.
Initially, that may seem unreasonable and restrictive, but there are lots of uses for implementing types without inheriting code. We have seen this with GUI listeners:
public class BallController extends WindowController implements ActionListener, AdjustmentListener
This means that our BallController can be used anywhere our program expects a WindowController, an ActionListener, an AdjustmentListener, or any supertype of these. It only inherits code from WindowController. Why?ItemListener, ActionListener, and AdjustmentListener do not provide any code to inherit. They simply set up types that we can implement. By implementing a type, we promise to define the methods for that interface. As a result, Java knows it can treat the new class as an instance of that type because the promised method must be supplied for the program to compile.
In this course, you will not use inheritance much in your own code aside from writing classes that extend Controller, WindowController, or ActiveObject, but it will be helpful to understand what is happening in those cases.
- Both implements and extends create subtypes
- extends inherits code from the supertype (whether class or interface)
- implements sets up a promise to implement the methods declared in the supertype