Wednesday 20 February 2013

13. Consider the class hierarchy shown below:

13.  Consider the class hierarchy shown below:


    
Consider the following code below:
1. DrivingUtilities du;
2. FourWheeler fw;
3. Truck myTruck = new Truck();
4. du = (DrivingUtilities)myTruck;
5. fw = new Crane();
6. fw = du;

Which of the statements below are true?

Choices:
a. Line 4 will not compile because an interface cannot refer to an object.
b. The code will compile and run.
c. The code will not compile without an explicit cast at line 6, because going
down the hierarchy without casting is not allowed.
d.The code at line 4 will compile even without the explicit cast.
e.The code will compile if we put an explicit cast at line 6 but will throw an exception at runtime.


Answer:-
C and D are correct.
A and B are obviously wrong because there is nothing wrong in an interface referring to an object.
C is correct because an explicit cast is needed to go down the hierarchy.
D is correct because no explicit cast is needed at line 4, because we are going up the hierarchy.
E is incorrect because if we put an explicit cast at line 6, the code will compile and run perfectly fine, no exception will be thrown because the runtime class of du (that is Truck) can be converted to type FourWheeler without any problem.

Discription:
http://www.cs.utexas.edu/~cannata/cs345/Class%20Notes/14%20Java%20Upcasting%20Downcasting.htm

No comments:

Post a Comment