Downcasting vs. templates/generics
To make these containers reusable, they hold the one universal type in Java: Object. The singly rooted hierarchy means that everything is an Object, so a container that holds Objects can hold anything.[8] This makes containers easy to reuse.
To use such a container, you simply add object references to it and later ask for them back. But, since the container holds only Objects, when you add your object reference into the container it is upcast to Object, thus losing its identity. When you fetch it back, you get an Object reference, and not a reference to the type that you put in. So how do you turn it back into something that has the useful interface of the object that you put into the container?
Here, the cast is used again, but this time youre not casting up the inheritance hierarchy to a more general type. Instead, you cast down the hierarchy to a more specific type. This manner of casting is called downcasting. With upcasting, you know, for example, that a Circle is a type of Shape so its safe to upcast, but you dont know that an Object is necessarily a Circle or a Shape so its hardly safe to downcast unless you know exactly what youre dealing with.
Its not completely dangerous, however, because if you downcast to the wrong thing youll get a run-time error called an exception, which will be described shortly. When you fetch object references from a container, though, you must have some way to remember exactly what they are so you can perform a proper downcast.
Downcasting and the run-time checks require extra time for the running program and extra effort from the programmer. Wouldnt it make sense to somehow create the container so that it knows the types that it holds, eliminating the need for the downcast and a possible mistake? The solution is called a parameterized type mechanism. A parameterized type is a class that the compiler can automatically customize to work with particular types. For example, with a parameterized container, the compiler could customize that container so that it would accept only Shapes and fetch only Shapes.
Parameterized types are an important part of C++, partly because C++ has no singly rooted hierarchy. In C++, the keyword that implements parameterized types is template. Java currently has no parameterized types since it is possible for it to get byhowever awkwardlyusing the singly rooted hierarchy. However, a current proposal for parameterized types uses a syntax that is strikingly similar to C++ templates, and we can expect to see parameterized types (which will be called generics) in the next version of Java.