About Question enthuware.ocpjp.v7.2.1497 :

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

Moderator: admin

Post Reply
pSteven
Posts: 2
Joined: Fri Jun 14, 2013 10:15 pm
Contact:

About Question enthuware.ocpjp.v7.2.1497 :

Post by pSteven »

class B {}
class B1 extends B {}
class B2 extends B {}
public class ExtendsTest
{
public static void main(String args[])
{
B b = new B();
B1 b1 = new B1();
B2 b2 = new B2();
// insert statement here
}
}

_______________________

A. b = b1; Not a problem because B1 IS-A B -- I get it.
D. b2 = (B2) b1;
"It will not compile because b1 can never point to an object of class B2."
I thought B2 IS-A B1 and B2 IS-A B. If so, a B1 reference could be assigned to a B2 object, and later transferred to a reference of its own type with the above cast.

Not so?

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

Re: About Question enthuware.ocpjp.v7.2.1497 :

Post by admin »

B2 is not a B1. B2 is a B.
-Paul.
If you like our products and services, please help us by posting your review here.

pSteven
Posts: 2
Joined: Fri Jun 14, 2013 10:15 pm
Contact:

Re: About Question enthuware.ocpjp.v7.2.1497 :

Post by pSteven »

It was late. I must have been tired. I did look at it for a few minutes before I asked, but now it's clear as day. But if the inheritance were thus . . .

class B {}
class B1 extends B {}
class B2 extends B1 {}

Then my question would have been valid. Sorry, and thanks.

emj211
Posts: 5
Joined: Wed Apr 17, 2013 2:41 pm
Contact:

Re: About Question enthuware.ocpjp.v7.2.1497 :

Post by emj211 »

I am a bit confused about the explanations for 2 answers here:

(option 3)
b2 = b;
It fails at Compile time as an object referenced by b may not be a B2, so an explicit cast will be needed.

(option 4)
b1 = (B1) b
It will pass at compile time but fail at run time as the actual object referenced by b is not a B1.

Option 3 is implying that if you provide an explicit B2 cast to b then it would work, but that is similar to option 4 and would produce a RuntimeException, right?

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

Re: About Question enthuware.ocpjp.v7.2.1497 :

Post by admin »

If you provide an explicit case, you are telling the compiler that at run time the object will be of the specified type, so the compiler lets it compile.
But at runtime, the JVM see that the actual object is not of the require type so it fail.

What this means is something may compile fine but may not necesarily run correctly.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 228 guests