Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting

 
Pawan Kumar
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A
{
int i=1;
void myFun()
{
System.out.println("Inside A's Constructor" );
}

}
class B extends A
{
int i=2;
void myFun()
{
System.out.println("Inside B's Constructor");
}

}
class Temp
{
public static void main(String[]args)
{
A a = new A();
B b=(B)a;
}

}
why it gives error on runtime ,but not on compile time
 
mansoor iqbal
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
at compile time, the compiler simply checks for existance of refernces.
even though ur casting is wrong, at runtime, it is quite possible that the references may point to right type of obects on which the casting operation can go thru.
due to the fact that till runtime, jvm cannot determine if the references are pointing to objects that can be cast correctly, the compiler performs a simple check if the references/objects exist.
 
Fawad Khan
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Pawan,
Mnasoor is quite right. At the compile time the object creation just needs the relationship among the classes. Thats is either one is subclass of the other. But at the compile time it seeks that u r doing the right casting or not. Like u r doing the casting of the super to sub or what else.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic