Misconceptions about the “extends” Keyword

Some Mammals can fly. Dog extends Mammal, but it can’t fly. The term “extends” leads to some misconceptions.

Generalization and Specialization

A Dog is a specialization of a Mammal. And the Mammal is a specialization of Animal. So Animal is a generalization of Mammal and Dog. But Java doesn’t use those terms. Instead you extend another class or interface.

The term is confusing because it seems that you extend something and get a new type that does more than the extended type. You can simply add more fields and methods and get more. This is the case for LinkedHashMap that works like a regular HashMap, but it has predictable iteration order.

But this kind of design is tricky. What about squares? Does a square extent a rectangle? Because it isn’t only rectangular but also of the same side length? Or does the rectangle extend the square because it has two instead of one side length (which translates to two inner fields to store the values)?

I explain the problems of inheritance in more detail and with alternatives in my post “OOP isn’t about inheritance”.

A Misnomer is some cases?

Since you actually can add new fields and methods it’s correct to say Mammal extends Animal. It can have some methods about breastfeeding that a Reptile would not have. And an extending class should actually not override the already implemented methods unless the superclass defines them to be overridden. Only abstract or empty methods of a superclass should be implemented in a subclass. So if you extend an abstract class you probably only override abstract methods. You do not necessarily add any new methods, but you still use the keyword “extends”. In that case you do not extend the type by methods (the API) but you complete the implementation.  If you define an interface that extends another interface then you probably do that to actually add more methods. Example: public interface Set<E> extends Collection<E>

As long as you understand what “extends” means it’s not a problem. But other languages don’t use the keyword. C# and Kotlin use a colon (class Dog : Mammal).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s