> I am preparing for the SCJP exam and I have run across this snipet of
> code that is confusing me.
[quoted text clipped - 9 lines]
> 9. a2.m1();
> 10. if (a2 instanceof Beta || a2 instanceof Gamma)
Note that the second part of this test is redundant.
If the object is a Gamma, it is also a Beta so the first
instanceof yields true and the second is never attempted.
If the object is not a Beta, it is also not a Gamma, so
if the first instanceof yields false, so will the second.
Either way, the result of the first instanceof is the
result of the entire expression.
> 11. a2.m2();
> 12. ((Beta)a2).m2();
[quoted text clipped - 23 lines]
> should also contain an m2() method. Right? The method is not private
> in Beta so it should be inherited.
Right.
> Why can I cast to Beta with no problem, but not to Gamma?
Because a[1] is not a Gamma, and you cannot just pretend
that it is one. As it happens, you only care about its Beta-
ish aspects -- but that's not the issue. The issue is that
you have told Java "You already know that the object is an
Alpha, but I happen to know that it is also a Gamma." Java
says "Interesting, if true -- I'll just take a quick look,"
and discovers that you were wrong: The object is not a Gamma.
If the object were in truth a Gamma, Java would next hunt
for its m2() method and would discover that m2() is inherited
from Beta. But Java never gets that far: As soon as it finds
that you were wrong about the nature of the object, it bails
out with a ClassCastException.

Signature
Eric Sosman
esosman@ieee-dot-org.invalid
jstorta - 06 Aug 2007 14:40 GMT
OMG. The red herrings on this test are going to kill me. All along I
was convinced that there was something about inheritance that I was
not understanding.
Now, as you explained, it makes perfect sense. This whole question
was really to test if I knew the short-circuit operator. Sadly, I
know about the short-circuit operators, but I just went off on the
inheritance tangent and never looked back.
Thank you for the explanation. It was exactly what I needed.
Joe Attardi - 06 Aug 2007 15:06 GMT
> OMG. The red herrings on this test are going to kill me. All along I
> was convinced that there was something about inheritance that I was
> not understanding.
I took (and passed, thankfully) the test 4 years ago (worked at Sun at
the time, so thankfully I didn't have to pay for it! woot!). A lot of it
is red herrings like the one you posted, and a lot of it is purely
memorization.
Try the Rules Roundup at javaranch.com to help you prepare, I used it a
lot during my study and it helped a lot.
Good luck on the test!

Signature
Joe Attardi
jattardi@gmail.com