This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Dear all, i had come across this particular question which has had me bugging all the day. Kindly help me out!!
Q. Which of the following code snippet when inserted individual at the commented line, will cause a java.lang.ClassCaseException?
The options are
(1) Greek f =(Beta)(Alpha)x;
(2) Alpha a = x;
(3) Greek f = (Alpha) x;
(4) Beta b = (Beta)(Alpha)x;
(5) Greek f = (Delta)x;
Would request you to kindly elucidate your solution!!
What happened when you inserted each line, one at a time, then compiled and ran it?
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Nov 07, 2010
For the first 4 options, the program compiles adn runs without showing any exception..!!
But thats not the case for the 5th option where the stance is given by
Greek f = (Delta)x;
This runs without returning any compliation eroor but returns the java.lang.ClassCastException during the runtime which states Beta cannot be cast to Delta. Hence 5th option is the solution.
But am not clear with how the stuff has worked out to be, specially with reference to the first and fourth option!!
Need your help please
on line 11, where the actual object is created, we make a Beta object. That is what's most important here - we have a Beta object.
then, still on line 11, we assign it to a Beta reference. So far, so good.
Assume we put in option #5: Greek f = (Delta)x;
'x' is a Beta reference, which conceivable COULD actually point to a Delta object, since Delta is a sub-class, so the cast is legal. We can assign that to a Greek reference, since Delta extends Beta extends Alpha which implements Greek - any Delta object is a Greek.
However, when we run things, we have a problem. When we try and do the cast of x to Delta, the ACTUAL OBJECT is a Beta. If the cast were allowed, then the Delta reference could try and call methods that aren't defined in the object. It's not until we have actual objects we can tell if the cast is allowed, since the cast is POSSIBLE.
If we were trying to cast a Beta to a ArrayList, the compiler know that can never happen, so it would be disallowed.
in option 1: Greek f =(Beta)(Alpha)x;
again, we have a Beta object. ALL Beta objects are Alpha objects, so the (Alpha)x cast is allowed. Then, since it is possible that a Alpha could be a Beta, the compiler allows this. Then, since all Betas are Greeks, we can assign it to that reference.
I believe that again, if line 11 were something like String x = new String("hello"), the compiler would complain. If it were Alpha x = new Alpha(), the compiler would allow it (again, it's POSSIBLE to down-cast from Alpha to Beta), but you'd get a run-time error.