Having to define a different class for similar containers (e.g. IntList, StringList, EquationList, ... or IntStack, StringStack, ...) is kind of a drag.
It would be nicer if we could have one class suited to all of these purposes.
This is known as polymorphism (having many forms).
Polymorphism is achievable in different ways in different languages.
It is one place in which Java differs considerably from C++.
In the present discussion, we focus on contains containers for data types which are actually objects.
Thus we want tobuild a polymorphic list (Polylist) which contains String's or Equation's, but not int's as such. We can come close to handling int's by using the idea of "wrappers", objects which simply contain a non-object value.
In Java, all objects inherit certain characteristics from an ultimate class called Object. If we create a list of elements of type Object, it turns out that we can put any type of object into the list.
In order to actually use the Object as a specific type of object, we have to tell the compiler that it really is of the more specific type. For example, if an object in a list is a String, we need to tell the compiler this before we can apply any String methods to it.
The way to tell the compiler that an Object has a more specific type is to cast it to that type. This takes the form of an expression with the type preceding and in parentheses:
Object o;o = new String("Hello");
.... use of o as an Object ....
System.out.println(o.length()); // ILLEGAL: Use of a String method on Object
String s = (String)o; // Cast o to String s
System.out.println(s.length()); // OK: use of a String method on s
Note that "upcasting" from a String to an Object, i.e. from specific to general, needs no special mention.
But "downcasting" from an Object to a String, i.e. from general to specific, does.
What if we try to downcast an Object which is not a String to a String?
A TypeCastException will be thrown.
We can test in advance whether a proposed casting will proceed using the instanceof built-in operator:
o instanceof String
returns true exactly in the case that o is a String.
Next Slide | Previous Slide | Contents |