Page 1 of 1

About Question enthuware.ocajp.i.v7.2.872 :

Posted: Fri Mar 22, 2013 1:05 am
by baptize
this question is very ambiguous!!!

You're giving us options to choose from based on:
A a = null;
AA aa = null;

No where in the question says that not even a hint:

A = new AA();

i suggest you rephrase this question.

Thanks.

Re: About Question enthuware.ocajp.i.v7.2.872 :

Posted: Fri Mar 22, 2013 6:41 am
by admin
There is no hint required to answer the question. The question is not ambiguous at all.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.872 :

Posted: Wed Apr 10, 2013 12:36 pm
by cblanche
The question is not ambigous but maybe the explanation could be improved.

((AA)a).doStuff(); will compile as this code do :
String s = null;
s.toString();
and throw a NullPointerException. If the object a is instanciated then we will have a ClassCastException.

You did a very good job for most of the explanation, thank you.

Re: About Question enthuware.ocajp.i.v7.2.872 :

Posted: Thu Nov 06, 2014 9:55 am
by Kevin_C
I had the answer correct, but I have a question above the explanation of the last option. This was the question:

Code: Select all

class A{ public int getCode(){ return 2; }
class AA extends A{ public void doStuff(){ } }
// Given the following two declarations, which of the options will compile?
A a = null;
AA aa = null;
Last option:

Code: Select all

((AA)a).doStuff();
With the explanation: "Once you cast a to AA, you can call methods defined in AA. Of course, if a does not point to an object of class AA at runtime, a ClassCastException will be thrown."

My question is: In this particular case will this option throw a ClassCastException or a NullPointerException (since a is null)? My guess is a ClassCastException since a doesn't point to an object of class AA (but instead it points to null), but I'm not sure.

Re: About Question enthuware.ocajp.i.v7.2.872 :

Posted: Thu Nov 06, 2014 9:05 pm
by admin
In this particular case it will throw NPE because a null can be cast as any class. Since a points to null, it can be cast as AA. So no CCE.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.872 :

Posted: Fri Nov 07, 2014 2:55 am
by Kevin_C
Ah ok, thanks for the answer. Maybe that should be added to the answer. It isn't really relevant to the question itself, but it's still good to know that it will throw a NullPointerException in this case, instead of a ClassCastException.

Something like: "Once you cast a to AA, you can call methods defined in AA. Of course, if a does not point to an object of class AA at runtime, a ClassCastException will be thrown.
In this case however, a is null, so there won't be a problem with the casting (since an AA-object can also be null). Instead, it will throw a NullPointerException."

Re: About Question enthuware.ocajp.i.v7.2.872 :

Posted: Sun Nov 09, 2014 10:42 pm
by admin
Added.
Thank you for your feedback!