Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Questions about casting

 
frank yang
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class SuperClass{
class SubClassA extends SuperClass{}
class SubClassB extends SuperClass{}
public void test(SubClassA foo){
SuperClass bar=foo;
}
}
which statement is true about the assignment in line 5?
A. The assignment in line 5 is illegal
B. The assignment in line 5 is legal, but throw a ClassCastException
C. legal and will always executes without throw an Exception
Which answer is correct?
Who can explain and give an example to run this code?
Thanks a lot
[ February 17, 2003: Message edited by: frank yang ]
 
Dan Culache
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that the correct answer is C. See 5.1.4 Widening Reference Conversions
where S is short for source (here SuperClass bar)and T is short for target (here SubClassA foo).
[ February 17, 2003: Message edited by: Dan Culache ]
 
Dan Culache
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
PS. What do you mean by "..give an example to run this code?"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic