The Artima Developer Community
Sponsored Link

Designing with Runtime Class Information
Using Runtime Class Information in Java Programs
by Bill Venners
First Published in JavaWorld, January 1999

<<  Page 3 of 6  >>


Legitimate uses of downcast and instanceof
Although downcasting and instanceof can be abused as described above, they also have legitimate uses. One common use of a downcast is to cast an Object reference extracted from a Collection to a more specific subtype. Here's an example:

class Hippopotamus {

    private String yawnAdjective;

    Hippopotamus(String yawnAdjective) {
        this.yawnAdjective = yawnAdjective;

    void yawn() {
        System.out.println(yawnAdjective + " yawn!");

// In file rtci/ex1/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

class Example1 {

    public static void main(String[] args) {

        ArrayList hippos = new ArrayList();
        hippos.add(new Hippopotamus("Big"));
        hippos.add(new Hippopotamus("Little"));
        hippos.add(new Hippopotamus("Technicolor"));


    // Client must pass a collection of Hippopotami
    static void makeHipposYawn(Collection hippos) {

        Iterator it = hippos.iterator();
        while (it.hasNext()) {
            Hippopotamus hippo = (Hippopotamus);

In this example, Iterator's next() method returns a reference to a Hippopotamus object, but the type of the reference is Object. The reference is immediately downcast to Hippopotamus, so that the yawn() method can be invoked on the object.

Note that instanceof was not needed here, because a precondition of the makeHipposYawn() method states that the Collection, passed in as parameter hippos, be full of Hippopotamus objects. Nevertheless, this code makes use of runtime class information because the JVM checks to see whether the cast is valid. In other words, the JVM makes sure the object referenced by the return value of next() really is a Hippopotamus. If not, the JVM will throw a ClassCastException and the makeHipposYawn() method will complete abruptly.

<<  Page 3 of 6  >>

Sponsored Links

Copyright © 1996-2018 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use