icon-mobile-menu.svg

Lecture Notes on Object-Oriented Programming

Object Oriented Instantiation

This is the most subtle form of relationship between classes. The potential confusion for people new to OO is that instantiation is what happens to create an object, yet this is a class-to-class relationship — no objects are involved. A parameterized class cannot have objects instantiated from it unless it is first instantiated itself (hence the confusing name for this type of relationship).

Another term for this relationship is "generics".

A generic class arises from a situation where the behavior of a class can be abstracted into something which is relevant to more than one type of state. The goal is to share the definition (in the class) of some behavior (i.e. the methods) across different data types.

For example, a Stack class has the same fundamental behavior whether it is holding Dogs, ints, Strings, etc. We shouldn't have to define a DogStack, IntStack, etc, as separate classes with nearly identical methods.

The common element across this "family" of potential stack classes is the data type being operated on. Let's abstract that out and create a generic Stack class which is parameterized on the type of data it is used to hold.

One way of implementing a generic class is to write it in terms of generic pointers such as void* in C, or id type in Objective C, or Object references in Java. The drawback of this is that a Stack class would be happy to store a mixture of objects. You could put one int, a Dog, and a Person in the same stack. There is no type checking that can be done, and hence no type safety.

Some languages, such as C++, support generics in a type safe fashion.

UML Representation