enthuware.ocajp.i.v7.2.872

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
shivtrip
Posts: 1
Joined: Sat Mar 07, 2015 8:56 pm
Contact:

enthuware.ocajp.i.v7.2.872

Post 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.

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: enthuware.ocajp.i.v7.2.872

Post 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.

mkodmkod
Posts: 1
Joined: Wed Jan 25, 2017 1:51 am
Contact:

Re: enthuware.ocajp.i.v7.2.872

Post 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.

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: enthuware.ocajp.i.v7.2.872

Post 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.

crazymind
Posts: 85
Joined: Mon Dec 24, 2018 6:24 pm
Contact:

Re: enthuware.ocajp.i.v7.2.872

Post by crazymind »

A a = null;
AA aa = null;

a = (AA)aa;

Does this assignment cause a NPE at runtime?

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: enthuware.ocajp.i.v7.2.872

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 11 guests