Monday, March 19, 2012

Is downcasting is possible regarding object in Java

By the begining of Languages downcasting has a issue.lets checks with C-language
void main()
{
long i=98765431;
byte j=(byte) i;
printf(j);
}
here data overflow and get unexcepted result.
Before discussing this topic first we go through the defination of Upcasting and downcasting


What is upcasting?UpCasting is defined as casting a reference of a parent class type to a type of a reference to a child class.
What is downcasting?Downcasting is defined as casting a reference of a child class type to a type of a reference to a parent class.


Upcasting can de done automatically means implicity in java and
Downcasting we have to do explicity else we get compile time error


now lets going through the defination of upcasting and downcasting code the java program and check....


class parent
{}
class child extend parent
{
public static void main(String args[])

{
line 1: parent p=new child(); //upcasting happened complile and run successfully
line 2: child c=new parent(); // downcasting but not explicity so we get compile time error
line 3: child c1=(child) new parent(); // downcasting explicity compile success but give run time error class cast exception
}
}


now just read the downcasting defination above and check line 3 of above program,we are doing downcasting but it not happening here.


many of us say downcasting is happened in java and gave the example mention below


class parent
{}
class child
{

public static void main(String args[])

{
line 1: parent p=new child(); //upcasting
line 2: child c=(child) p; //downcasting,compile and run success
}
}


look carefully at line 2 we really doin downcasting,i don't think downcasting is not suitable word here we are doing here typecasting

in simple we can say that:
at line 1 we create object of child and say that you are parent type
and at line 2 we again saying to same child object that you are child type here where is the parent object that we are casting to child type..????

what is my opion on this issue is there i posted on this blog....
still have little bit confusion and hoping someone to clear this confusion

If you really enjoyed this
give feedback
thanks...... :)