In java there is a class called Vector. The class Vector effectively models a resizable array. You can add elements to the array remove them and randomly access them.

int add(Object obj)

Object elementAt(int index)

The above two methods allow you to add an element and then access an element inside the vector. Notice that they accept instances of class Object. This means that the methods are polymorphic. As Object is the root of all object hierarchies, these methods will accept instances of any class.

Vector v = new Vector();

Payslip p = new Payslip();

v.add(p);

Object o = v.elementAt(0);

The above code adds a Payslip object to a vector then retrieves it. Unfortunately the elementAt method returns instances as class Object. This means if we wrote Payslip o = v.elementAt(0) would result in a error. In order to get the Payslip instance back we must cast it. We want to cast the instance from Object to Payslip.

Payslip o = (Payslip) v.elementAt(0);

The syntax of casting is basically the class you are casting to in brackets. Casting only works if the class of the instance you are casting is part of the class hierarchy you are casting to.

String s = (String) v.elementAt(0);

The above line would fail, even though it will compile. It produces a runtime exception as the instance stored at position 0 in the vector ( Payslip) is not a String, nor is String part of the hierarchy of Payslip.

Casting goes arm in arm with polymorphism and allows us to write very robust and powerful code. However it is a source of many errors. For example consider the following line.

int bignumber = 999999999999; // is set at 32 bits or 4 bytes

byte smallnumber = (byte) bignumber; // a byte is 8 bits or one byte

This line will compile and run, although it will have a warning at compile time. The problem is that you are trying to put a very large number into a smaller space. As such the number will be cut off and you will get unexpected results. Casting must be used with care, as these sorts of errors are all too common in java.