Monday, September 21, 2009

Casting Objects

One Object reference can be type cast in to another object reference.That class can be to its own class type or to one of its super class or sub class typees or interface.


In Java we can do Object casting in two types.

# Up Casting
# Down Casting

Let's say we cast a reference along the class hierarchy in a direction from the root class towards the sub class.So this is kown as the Down Casting.

When we cast it towards the sub class to super class , It's known as Up Casting.
In this case we do not need to use class operater.

We will take a look at a Simple Example..

Ex A.
UpCasting

Class Animal{
}
Class Dog extends Animal{
}
Class DogTest{
public static void main(String[]args){

Dog dog=new Dog();
Animal animal=dog; //Up Casting.This is ok with no explicit cast.
Animal animal=(Animal) dog; //Up cast ok with explicit cast.

Ex : B

Down Casting

Class Animal{
}
Class Dog extends Animal{
}
Class DogTest{
public static void main(String[]args){

Animal animal =new Animal();
//Dog d=animal; //we cant write it like this .
Dog d=(Dog)animal;//now this is ok .But compiles it .but gives a run time error.
}

imp:- When we doing Down casting we can compile it. but when we run it it gives an error like this.

java.lang.ClassCastException.

No comments:

Post a Comment