It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting problem" Watch "Casting problem" New topic
Author

Casting problem

Mushraf Khan
Ranch Hand

Joined: May 04, 2011
Posts: 37
Gooday Everyone.

I really need your great help, if anyone could please help me to explain the below line. I have tried very hard to understand, but in vain. Maybe my some concepts are wrong. Please help me. This is from Examlab Practise test1 Question 29

1. interface Min{}
2.
3. class A{}
4.
5. class B extends A implements Min{}
6.
7. class C extends B{}
8.
9. public class CCExp{
10. public static void main(String args[]){
11. A a=new A();
12. B b=new B();
13. C c=new C();
14. Min m=null;
15. b=(C)m;
16. m=(Min)b;
17. A a2=(A)m;
18. B b2=(B)a2;--------the reference type of a2 is A, then we cannot cast A to B, it will give class cast exception. But the answer is that it
compiles and excutes. Please can anyone explain how is this possible.
19. Min m2=(C)b2;
20. C c2=(C)m2;
21. }
22. }
Astha Sharma
Ranch Hand

Joined: Oct 15, 2011
Posts: 249

Mushraf Khan wrote:Gooday Everyone.

I really need your great help, if anyone could please help me to explain the below line. I have tried very hard to understand, but in vain. Maybe my some concepts are wrong. Please help me. This is from Examlab Practise test1 Question 29

1. interface Min{}
2.
3. class A{}
4.
5. class B extends A implements Min{}
6.
7. class C extends B{}
8.
9. public class CCExp{
10. public static void main(String args[]){
11. A a=new A();
12. B b=new B();
13. C c=new C();
14. Min m=null;
15. b=(C)m;
16. m=(Min)b;
17. A a2=(A)m;
18. B b2=(B)a2;--------the reference type of a2 is A, then we cannot cast A to B, it will give class cast exception. But the answer is that it
compiles and excutes. Please can anyone explain how is this possible.
19. Min m2=(C)b2;
20. C c2=(C)m2;
21. }
22. }

Although the reference type of a2 is A but it is referring towards null which can no doubt be referred by reference of B. So this will compile and run fine. It would have been giving Class cast exception if a2 would have been referring object of A.


Astha - OCPJP 6 (90%)
Mushraf Khan
Ranch Hand

Joined: May 04, 2011
Posts: 37
Thanks a lot Astha. That was really easy to understand, had this doubt for last 15 days . Thanks a lot.
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Casting cannot be done only if the type being casted is not it's parent.

Mushraf Khan
Ranch Hand

Joined: May 04, 2011
Posts: 37
Thanks alot John. Example was good understanding to clear the doubts
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting problem