TestCast.java


public class TestCast {
   public static void main (String[] args){
	
      Cat       aCat  = new Cat();
      Seal      aSeal = new Seal();
      FourLegs  a4leg;
      SeaMammal aSeaMammal;
      Mammal    aMammal;
      Animal    aAnimal;

      aMammal    = aSeal;     // aSeal is a Mammal
      a4leg      = aCat;      // aCat is a FourLegs
      aAnimal    = aMammal;   // aMammal is a Animal
      aSeaMammal = aSeal;     // aSeal is a SeaMammal

      //a4leg   = aSeal;      // aSeal is not a FourLegs
      //aSeal   = (Seal)aCat; // cannot cast to sibling class even w/ a cast

      // The following 4 are examples of improper casting
      // They will succeed at compile time, and throw RuntimeExceptions.
      // When running the program, you only can see one at a time.
      // Commenting out the previous one(s)
      // you will see the next RuntimeException.

      a4leg = (FourLegs)aSeal;// cast obj to an interface is ok at compile time
                              // will throw ClassCastException at run time.
                              // since aSeal is not a FourLegs

      aSeal = (Seal)a4leg;    // cast interface to an obj is ok at compile time
                              // will throw ClassCastException at run time.
                              // since FourLegs cannot be a seal.
	                           
      aCat  = (Cat)aAnimal;   // cast superclass to its subclass is ok 
                              // at compile time.
                              // will throw ClassCastException at run time.
                              // since aAnimal is actually a Seal, not a Cat
	                           
      aSeaMammal = (SeaMammal)a4leg; // cast between irrelavent interfaces is ok
                                     // at compile time,
                                     // will throw ClassCastException at run time.
                                     // since cat is not a SeaMammal

   }
}

class Animal {
}
class Mammal extends Animal{
}
class Whale  extends Mammal implements SeaMammal{
}
class Seal   extends Mammal implements SeaMammal{
}
class Cat    extends Mammal implements FourLegs{
}
class Rat    extends Mammal implements FourLegs{
}
interface FourLegs {
}
interface SeaMammal {
}

Last updated: 12-10-2002
Copyright © 1999 - 2003 Roseanne Zhang, All Rights Reserved
[ Java certification page] [ SCJP FAQ] [ JavaChina]