About Question com.enthuware.ets.scjp.v6.2.207 :
Moderator: admin
About Question com.enthuware.ets.scjp.v6.2.207 :
Please convince me why b1 = (B1) b; will fail at run time. It seems to be a legitimate downcast.
-
- Site Admin
- Posts: 10385
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.207 :
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.
You might want to try it out.
-
- Posts: 1
- Joined: Tue Nov 12, 2013 10:13 am
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.207 :
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.
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.
-
- Site Admin
- Posts: 10385
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.207 :
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.
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.
Who is online
Users browsing this forum: Google [Bot] and 10 guests