Casting Rules in Java Programming

Casting Rules in Java Programming

Previous Home Next

 

Conversion of data from one type to another type is called type casting.

                         
It is sometimes necessary to convert a data item of one type to another type.
Conversion of data from one type to another type is known as type casting.
 In java one object reference can be type cast into another object reference.
 This casting may be of its own type or to one of its subclass or superclasss types or interfaces.
 Some compile time or runtime type casting rules are there in java.
 Some circumstances requires automatic type conversion, while in other cases it must be "forced" manually (explicitly).

Automatic conversion:-
Sometimes, as with primitives, the type conversion is automatically handled by the compiler.
Consider a super class vehicle with a subclass Scorpio

Java follows two type of casting

  1.Up casting:-
Casting a reference with the class hierarchy in a direction from the sub classes towards the root then this type of casting is termed as upcasting. Upcasting does not require a cast operator.
 
2.Down casting
:-On the other hand, casting a reference with hierarchal class order in a direction from the root class towards the children or subclasses, then it is known as downcasting.

Explicit conversion casting:-
When automatic conversion does not work ,when data type requiring more storage converting into data type requiring less space e.g. long to int data type.
 


 Automatic conversion
class Conversion 
{
Vehicle v;
Scorpio s;
public void convert () {
s = new Scorpio ();
v = s;
}
}


Previous Home Next