File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reference variable casting w.r.t interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference variable casting w.r.t interfaces" Watch "Reference variable casting w.r.t interfaces" New topic

Reference variable casting w.r.t interfaces

Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
Source: Get Certified Exam Lab / Practice Exam 1, Q No. 29
Which of the lines cause exception?
Answer: None of the line cause exception.

I am able to understand till line 16.

But in line 17, there is a casting done on m with reference variable of type A. My doubt is: When there is no relation between A and Min, how is this reference variable casting working? What are the rules behind this? And beyond line 17 too, I am getting confused

I am having a tough time understanding this. If anyone could explain this concept (casting with respect to interfaces specifically) in a simple way, I would be pleased.

Thanks in advance.
[ November 20, 2008: Message edited by: Rekha Srinath ]
Ankit Garg

Joined: Aug 03, 2008
Posts: 9280

Well line 17 works as A and Min have a common sub type B. So the object represented by m might point to an object of class B this is why the assignment worked. Even the cast is not neccesary. If however m points to an object of type other than B, then there will be a ClassCastException at runtime but in the question we are concerned about compilation only. This problem that I posted when I first came to javaranch is also a similar problem but it is related to instanceof...
[ November 20, 2008: Message edited by: Ankit Garg ]

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
Thanks Ankit..I think I am getting it. Will get back in case of further doubts.
I agree. Here's the link:
subject: Reference variable casting w.r.t interfaces
Similar Threads
Assigning references problem
ExamLab Question
Casting problem
doubt in class hierarchy
casting from examlab