This involves assignment conversion and explicit casting.
And remember, for assignment conversion of x to y; x must be an instanceof Y (class for object y). If you want to do the other way, you need explicit casting.
For assignment conversion, there is only one check made by compiler. For above example, if you assign y to x, a complier error will occur.
For explicit casting, there are actually two checks. One is made by compiler and one made by runtime. For above example, x = (X) y is okay for compiler b/c y is converted to x by casting. This is syntaxically right to compiler. However, during runtime, another check was made to see if it is possible to convert y to X
and you know you can not (because y is not an instanceof X).
Hope this explains it.
Originally posted by mohammed mustafa:
can any one explain me the concept behind explicit casting ; in one of khalids mocks there was a question on casting
class A {}
class B extends A {}
class C extends A {}
public class Q3ae4 {
public static void main(String a[])
{
A x=new A();
B y=new B();
C z=new C();
// insert statement here
}
}
Choices :
(i) x=y;
(ii)z=x;
(iii) y=(B)x;
(iv) z=(C)y;
(v) y=(A)y;
I could not understand why can't we cast like the choice 'iii'
above since y is the reference to the sub class of A