About Question com.enthuware.ets.scjp.v6.2.207 :

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

Moderator: admin

Post Reply
ETS User

About Question com.enthuware.ets.scjp.v6.2.207 :

Post by ETS User »

Please convince me why b1 = (B1) b; will fail at run time. It seems to be a legitimate downcast.

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

Re: About Question com.enthuware.ets.scjp.v6.2.207 :

Post by admin »

The actual object being pointed to by b at runtime is of class B. B is not B1. So you can't assign it to a reference of class B1.
You might want to try it out.
If you like our products and services, please help us by posting your review here.

liemkit
Posts: 1
Joined: Tue Nov 12, 2013 10:13 am
Contact:

Re: About Question com.enthuware.ets.scjp.v6.2.207 :

Post by liemkit »

Am I correct in thinking this is about the reference variable itself?
b1 has type B1 and, even though you cast to B1, b is still of type B.
You cannot change the type of an reference variable.

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

Re: About Question com.enthuware.ets.scjp.v6.2.207 :

Post by admin »

This is a about the actual object that is referred to by the variable. You can't cast a base class object to a subclass object. For example, you can't cast Employee object to CEO object (assuming that CEO extends Employee). You can use a reference variable of type Employee to refer to a CEO though.

Employee e = new CEO(); //valid
CEO ceo = (CEO) e; //valid because e points to an object that is a CEO.

Employee e2 = new Employee(); //valid
ceo = (CEO) e2;// Invalid - Will fail at run time - because e2 points to an object of class Employee, which is is not a CEO.

HTH,
Paul.
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 224 guests