| Author |
Problem with output( Casting)
|
Rohan Deshmkh
Ranch Hand
Joined: Aug 31, 2012
Posts: 127
|
|
This is a question from enthuware's.
And the following declarations:
A a = new A();
B b = new B();
Identify options that will compile and run without error.
1. a = (B)(I)b;
2. b = (B)(I) a;
3. a = (I) b;
4. I i = (C) a;
I am not able to understand it's output.The correct answer is option 1.How? I assumed it is correct because b is an instance of B.No matter what's on the left side of = and not taking into consideration about(I) in the expression (B)(I)b
Option 2 is not correct beacuse a is not an instance of B.
Why is option 3 not correct.b is an instance of I(Indirectly).Look's like now my assumption of not looking on the left side of = is false and now it does matter to whom you are assigning the variable.
Option 4 is wrong because a is a A but A is not C.So we cannot cast this way.
Am i correct?
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12921
|
|
Option 3 is wrong because you cannot assign any arbitrary I to a variable of type A.
Class A implements interface I, but there could be other classes, unrelated to A, that also implement I. If option 3 were possible, you could do:
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
harshvardhan ojha
Ranch Hand
Joined: Jul 26, 2007
Posts: 157
|
|
|
Hi Rohan, why you are assuming that left side of = doesn't matter? Although your other assumptions seems to be correct only look at option C, you need to make your understanding about how a subclass casted to interface cant be assigned to superclass. Again superclass is not subclass.
|
 |
Tony Docherty
Bartender
Joined: Aug 07, 2007
Posts: 1156
|
|
1. a = (B)(I)b;
Type B is upcast to I - Legal as B extends A which implements I
Type I is downcast to B - Legal as the object in this case is of type B
Type B is assigned to variable of type A - Legal, you can always assigned an object to a variable which is a super type. ie it is always legal to upcast.
2. b = (B)(I) a;
Type A is upcast to I - Legal as A implements I
Type I is downcast to B - Illegal as the object in this case is of type A and can't be downcast to type B
3. a = (I) b;
Type B is upcast to I - Legal as B extends A which implements I
Type I is assigned to variable of type A - Illegal, you can't downcast unless you specify the type you are downcasting to.
4. I i = (C) a;
Type A is downcast to C - Illegal as the object in this case is of type a and can not be downcast to type C.
.Look's like now my assumption of not looking on the left side of = is false
Yes you are right in realising your assumption is wrong. See the answer in your other thread.
|
 |
Rohan Deshmkh
Ranch Hand
Joined: Aug 31, 2012
Posts: 127
|
|
Ok , i finally got it.
Thanks to everyone , especially Tony Docherty for nice and step by step explanation.
|
 |
 |
|
|
subject: Problem with output( Casting)
|
|
|