Java Polymorphism – Why Return or Assign to a Supertype Rather Than Implementation Type?

javapolymorphism

I have been doing a lot of reading about polymorphism, inheritance and typing (specifically how it applies to Java).

I have seen some interesting examples, but not much explanation as to why.

I.e.:

    Person p = new Student();

I am assuming we have a Person class and a Student class which extends the Person class.

My question is: Why would you want to do this kind of assignment at all?

Best Answer

Using something like that, we can have many different types that all support the interface of Person, which means we can write code that takes a Person and doesn't care which specific type it is, as long as it supports whatever a Person supports.

You might not anticipate an AncientZombieLord class when first writing some generic code that takes a Person, but if AncientZombieLord is a subtype of Person, all the code written for a Person will work for AncientZombieLord too.

If you take a look at Java's collections, there are ArrayList and LinkedList types, which are both subtypes of List. They have different performance characteristics, but both support a common interface, so I can write code that uses a List that will work with either kind of list.

You can use this sort of thing to write a generic algorithm that uses one type now, and then switch it to something else without needing to fiddle with a lot of code -- just change one type.

In general, being able to abstract away from details that don't matter is a big win.