|
-
September 28th, 1999, 06:11 AM
#1
Type Casting - II
Hi.....
I have a question & its answer but i am confuse about it.
If any one clear about thsi question explain me.
Question is
class class1{}
class class2 extends class1{}
class class3 extends class3{}
When is the following method valid?
public class1 castMe(class3 ref){
return (class1)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
Answer : A
-
September 28th, 1999, 08:06 AM
#2
Re: Type Casting - II
Hi,
I think there is s typo in your question.
Class3 extends Class2 and not Class3.
Anyway, to answer your question about the typecasting:
1. A Subclass Reference can always be assigned to a Superclass Reference.
i.e Class1 = (Class1)(Class3 ref) is always correct. The typecast here is redundant.
2. But a Superclass is not automatically a Subclass. Therefore, if you use:
Class3 = (Class3)(Class1 ref), you could get a ClassCast Exception if Class1's "ref" was not actually referencing a subclass object.
Hope it answers your question,
Uma.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|