kirran

Wednesday, June 20, 2012

Java Object type casting

Java Object type casting

Converting object reference of one type to another type is called Java object typecasting. Casting is a programming term that means, effectively, converting a value or an object from one type to another. The result of a cast is a new value or object; casting does not change the original object or value.
The class of the object you're casting and the class you're casting it to must be related by inheritance; that is, you can cast an object only to an instance of its class's sub- or superclass-not to any random class. Casting downward in the class hierarchy is automatic, but casting upward is not.

There are two types of object typecasting:
1. upcasting 
2. downcasting


Upcasting: Upcasting is implicit and safe. Here subclass object is converted to superclass object, because a subclass object is also a superclass object.

Downcasting:Down-casting is potentially unsafe, because you could attempt to use a method that the derived class does not actually implement. With this in mind, down-casting is always explicit, that is, we are always specifying the type we are down-casting to. Converting an instance of a subclass to an instance of a superclass loses the information

Upcasting vs Downcasting

Given Below is a program which easily demonstrates the difference between Upcasting and downcastin in Java.

_____________________________________________________
Vehicle v1  = new Car();  / /Right . upcasting or implicit casting

Vehicle v2= new  Vehicle();

Car c0 = v1;  // Wrong compile time error "Type Mismatch"

  //Explicit or downcasting is required
 
Car c1 = (Car) v1 // Right. downcasting or explicit casting . v1 has a knowledge    //of Car due to line 1
 
Car c2= (Car) v2;  //Wrong Runtime exception ClassCastException because v2    //has no knowledge of Car.
 
Bus b1 = new BMW();  //Wrong compile time error "type mismatch"
 
Car c3 = new BMW(); //Right. Upcasting or implicit casting
 

Car c4 = (BMW) v1; // Wrong Runtime exception ClassCastexception
 
Object o = v1;  //v1 can only be upcast to its parent
 
Car c5 = (Car) v1; // v1 can be downcast to Car due to line 1    _____________________________________________________
  • ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance.  Use exception handling mechanism to catch ClassCastException
  • Use the instanceof operator to guard against incorrect casting.

No comments:

Post a Comment