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.

Summry

  • 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

results matching ""

    No results matching ""