Page 1 of 1

enthuware.ocajp.i.v7.2.872

Posted: Sat Mar 07, 2015 9:13 pm
by shivtrip
Hi,
the question mentioned reads as below-

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;


One of the answers marked as correct is a=(AA)aa;

Can you provide an explanation around the same as you are again casting a derived class object to itself and assigning the same to base class? I did not understand the principle. A help here would be appreciated.

Re: enthuware.ocajp.i.v7.2.872

Posted: Sun Mar 08, 2015 3:02 am
by admin
The basic principle is that the cast at run time will work if the actual object pointed to by the reference variable satisfies the is-a test with the class to which it is casted. So when you do (AA) aa; you have to see whether the object pointed to by aa is-a AA? If it is true then the cast will work.

Second thing to see is if the casted object satisfies the is-a test with class of the variable to which it is assigned. In this case, you have to see whether AA is-a A. If it is, then the assignment will work otherwise not.

HTH,
Paul.

Re: enthuware.ocajp.i.v7.2.872

Posted: Wed Jan 25, 2017 1:59 am
by mkodmkod
The review answers (option 6) from enthuware says NullPointerException is thrown because 'a' points to null. Which is incorrect. I am not seeing any null pointer exception with the below. A a = null; AA aa = new AA(); aa = (AA) a ;
Can someone please justify option 6.

Re: enthuware.ocajp.i.v7.2.872

Posted: Wed Jan 25, 2017 4:47 am
by admin
Option 6 is ((AA)a).doStuff();
Observe that it makes a method call on a, which you are not doing in your code. NPE will be thrown when you use a null reference to make a method call or access an instance field.

Re: enthuware.ocajp.i.v7.2.872

Posted: Mon Dec 31, 2018 4:06 pm
by crazymind
A a = null;
AA aa = null;

a = (AA)aa;

Does this assignment cause a NPE at runtime?

Re: enthuware.ocajp.i.v7.2.872

Posted: Mon Dec 31, 2018 9:48 pm
by admin
No, it cannot throw a NPE. As mentioned in my reply above, "NPE will be thrown when you use a null reference to make a method call or access an instance field.".

Also, please note that we do not encourage spoon-feeding. We prefer the users to actually try compiling and running the code and then post their doubt with along with their output.