Tests the class type of an object using the isInstance method (preferred over instanceof operator).

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

interface Barking {}

class Mammal {}

class Canine extends Mammal {}

class Dog extends Canine implements Barking {}

class Retriever extends Dog {}

public class InstanceOf {
  public static void main(String[] args) {
    Canine wolf = new Canine();
    Retriever rover = new Retriever();

    System.out.println("Testing instanceof:");
    report(wolf, "wolf");
    System.out.println();
    report(rover, "rover");

    System.out.println("\nTesting isInstance:");
    Class barkingClass = Barking.class;
    Class dogClass = Dog.class;
    Class retrieverClass = Retriever.class;
    System.out.println("  Does a retriever bark? " +
                       barkingClass.isInstance(rover));
    System.out.println("  Is a retriever a dog? " +
                       dogClass.isInstance(rover));
    System.out.println("  Is a dog necessarily a retriever? " +
                       retrieverClass.isInstance(new Dog()));
  }

  public static void report(Object object, String name) {
    System.out.println("  " + name + " is a mammal: " +
                       (object instanceof Mammal));
    System.out.println("  " + name + " is a canine: " +
                       (object instanceof Canine));
    System.out.println("  " + name + " is a dog: " +
                       (object instanceof Dog));
    System.out.println("  " + name + " is a retriever: " +
                       (object instanceof Retriever));
  }
}