Java Object Casting.

Java Object Casting

  • A cast, instructs the compiler to change the existing type of an object reference to another type.
  • In Java, all casting will be checked both during compilation and during execution to ensure that they are legitimate.
  • An attempt to cast an object to an incompatible object at runtime will results in a ClassCastException.
  • A cast can be used to narrow or downcast the type of a reference to make it more specific.
    Casting example:
    class Animal {
    }
    
    class Cow extends Animal {
    }
    
    public class ObjectCasting {
      public static void main(String args[]) {
        Animal creature;
        Cow daisy = new Cow();
        creature = daisy;        // OK
        creature = new Animal();
        //daisy = creature;     // Compile-time error, incompatible type
        daisy = (Cow) creature;   // OK at Compile-time, but it throws exceptions at run time.
      }
    }
    You can check this with instanceof before you perform the cast:
    ...
        if ( creature instanceof Cow ) {
            Cow cow = (Cow)creature;
        }
    ...
    Casting example with the instanceof test :
    class Animal {
      @Override
      public String toString() {
        return "I am an Animal"; 
      }
    }
    
    class Cow extends Animal {
        @Override
      public String toString() {
        return "I am a Cow"; 
      }
    }
    
    public class ObjectCasting {
      public static void main(String args[]) {
        Animal creature;
        Cow daisy = new Cow();
        System.out.println( daisy); // prints: I am a Cow
        creature = daisy;        // OK
        System.out.println(creature); // prints: I am a Cow
        creature = new Animal();
        System.out.println(creature); // prints: I am a Animal
    //    daisy = creature;     // Compile-time error, incompatible type
        if (creature instanceof Cow) {
          daisy = (Cow) creature;   // OK but not an instance of Cow
          System.out.println( daisy);
        }
      }
    }
    The result of this is:
    I am a Cow
    I am a Cow
    I am an Animal
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.