This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting" Watch "Casting" New topic


Pawan Kumar

Joined: Sep 04, 2000
Posts: 23
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

Joined: Aug 14, 2000
Posts: 91
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

Joined: Feb 13, 2001
Posts: 36
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.

Seeking Certification
I agree. Here's the link:
subject: Casting
It's not a secret anymore!