Click to See Complete Forum and Search --> : ClassCastExcep


Deepa Natarajan
July 31st, 1999, 08:07 PM
Hi,

I have 2 questions of the classCastingExcep concept.

Source code 1:

class parent{};
class D1 extends parent{}
class D2 extends parent{}

class Test{
public static void main(){

parent p1 = new parent();
D1 d1 = new d1();
D2 d2 = new d2();

d1 = (D1)p;

}
}

Which ans is correct?
1.illegal both compile and runtime
2.Legal at compile bit fails in runtime
3.Legal at compile and runtime

Source Code 2:

class Test{
static void s(){
S.o.p("***");
}
}

class D1 extends Test{
static void s(){
S.o.p("***");
}
public static void main(){
Test t1 = new Test();
t1.s();
D1 d1 = new D1();
d1.s();

d1 = (D1)t1;
d1.s();
}
}

Both compile but give a runtime exception.Why?What is the change and what is the concept behind?

Thanks,
Deepa

unicman
August 1st, 1999, 11:10 AM
It is very simple.

E.g. consider source code-1 in ur example. Here if u declare a variable of parent class (i.e. p1), it can hold object of any class derived from the parent class (i.e. parent)

So when u do '(D1)p1', compiler doesn't know what object 'p1' is having. As it is possible that a object of class 'D1' can be hold in 'p1', it assumes that this statement is correct.

But at run-time it knows that object held in 'p1' is not of type 'D1' so it gives u ClassCastException.

In the second example also, 't1' can hold object of class 'D1', so it assumes at compile time that the statement is correct. But at run-time it knows that the object in 't1' is not of class 'D1' at all. So it gives error.

- UnicMan
http://members.tripod.com/unicman