File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Casting" Watch "Casting" New topic
Author

Casting

devi nachimuthu
Greenhorn

Joined: Jan 07, 2003
Posts: 10
The following defines an object hierarchy.
class class1{}
class class2 extends class1 {}
class class3 extends class2 {}
1. when is the following method valid?
public class3 castMe(class1 ref) {
return (class3)ref;
}
a) always
b) never
c)if and only if ref references an class3 object
d) if and only if ref references an class2 object
The given answer is c. I cannot understand why it is c. Can some body explain...?
Thanks
Sachin Kombrabail
Greenhorn

Joined: Aug 28, 2000
Posts: 14

There can be three ways in which castMe can be called. Let us see how each will react.
1. If you pass an instance of C1 then the method will try to cast into C3 this will give you a ClassCastException since java does not support downcasting.
2. If you pass an instance of C2 then the same message as in C1.
3. If you pass an instance of C3 that will go through.
So (c) is the only answer for your question.
devi nachimuthu
Greenhorn

Joined: Jan 07, 2003
Posts: 10
I agree with you sachin, but how can i pass C1 to C3. There is no relation between Class1 and Class3, Class3 is inheriting from Class2. So how can we pass C1 to C3...?
 
 
subject: Casting
 
Threads others viewed
Accessing component from main class.... Help!
Help with HQL
Top level clases
Bug:GhostsFoundInClasspath
Please HELP...Devaka Exam Test 2 Number 69. I totally don't understand it.
developer file tools