This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
This code/question is from the SAI sample e-practice exam:
The question is:
Which code, inserted at line 11, will compile, but cause an exception to be thrown at runtime?
The answer and explanation are:
Option D is correct. Options A and C will NOT compile, option B will compile and run. Option D throws an exception because type Alpha has no m2 method.
But when I try option D, the code compiles and Runs fine. No exception is being thrown. The above answer and explanation doesn't make sense to me. In fact none of the answer choices seem to be correct. I am confused. What is the right answer and why?
The answer is right. It does throw an exception on my system. Can you create a new GreekTest.java file in an empty folder with the code you posted, recompile it and then run it to see the output. Sometimes existing .class files can result in unpredictable behavior...
Short circuit operator(||) check its first boolean expression, if that is false only, it will check the second boolean expression.... Here you can't cast a Beta object to a Gamma object.. so, ClassCastException will be thrown.....
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
a2.m2(); : Reference variable is of type Alpha, so the compiler sees that Alpha doesn't have m2 method
((Beta)a2).m2(); : Will run and compile because you are casting an Alpha reference variable as Beta. It is as if the reference variable is Beta, which has method m2()
((Alpha)a2).m2(); : You are casting reference variable Alpha as Alpha so it's just as if you would have written a2.m2();
((Gamma)a2).m2(); : Beta cannot be cast to Gamma. This is a downward cast and there is no guarentee that whatever Gamma can do, Beta can do