Pre-assessment notes

Subclassing and polymorphism

The key things I wanted you to say were: subclassing lets you use object oriented polymorphism (this is far more important than that it lets you save a little typing); but it introduces tight coupling between the subclass and the superclass. To decide when it's sensible to make T a subclass of S, the main thing you should ask yourself is: is it true that every T is an S? The reason why this is the right question is that then, a client written to handle Ss should indeed be able to handle Ts automatically, which is what OO polymorphism will give you.

Polymorphism literally means having many shapes. You've actually encountered two different kinds of polymorphism in the first year, and both of them occur in Java. The one you see where Java uses generics, e.g. ArrayList<String>, ArrayList<Integer>, is called parametric polymorphism, and Haskell also uses this extensively. (In fact, Java didn't have this kind in the beginning, and our very own Phil Wadler was instrumental in getting it added.) However, the main one is what's usually called object oriented polymorphism, or sometimes ad hoc polymorphism. It's when the same client code can work with objects that have many forms, because they share a common interface which is all the client code needs to know. For example, if a client is written in terms of Animal and only needs to access methods that are understood by any Animal, then the same client code can work with any object which is an instance of a subclass of Animal.

This still applies if subclasses implement methods differently, though note that it's still polymorphism if they don't (e.g., if one subclass of Animal just added an attribute and/or method that the client code never mentioned).

Several people mentioned method overloading, but that isn't usually considered a kind of polymorphism, though well done for remembering this feature of Java (and other languages): where you have two methods with the same name, but different arguments, they can contain completely different code. See this tutorial page if this means nothing to you.

Overall I saw a lot more right answers to these question than I did when I asked the same questions last year, which is pleasing!


This page is maintained by Perdita Stevens (perdita@inf.ed.ac.uk)


Home : Teaching : Courses : Seoc : 2015_2016 : Preassessment 

Informatics Forum, 10 Crichton Street, Edinburgh, EH8 9AB, Scotland, UK
Tel: +44 131 651 5661, Fax: +44 131 651 1426, E-mail: school-office@inf.ed.ac.uk
Please contact our webadmin with any comments or corrections. Logging and Cookies
Unless explicitly stated otherwise, all material is copyright © The University of Edinburgh