• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in casting

 
Jyothsna Panchagnula
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Source:-http://www.go4java.20m.com/mock1.htm
.Which one of the following statements will give you an Exception when
placed at line no.10?Select one correct answer.

I see that all the choices are correct.


thanks,
Jyothsna
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




Hi Jyotshna,

2. is implicit upcasting.
3. is explicit downcasting with no error.
4. is implicit upcasting.

The problem is 1. You are doing explicit downcasting, so it will compile fine, but at runtime the JVM will realize that reference a actually doesn't point to a BB object, so a ClassCastException will be thrown.

The difference between 1. and 3. is that in 1., the a reference points to an AA object, which is not a BB object, so it is a runtime error. However, 3. works fine because reference c, which is of type AA, actually points to a BB object.
[ December 23, 2008: Message edited by: Ruben Soto ]
 
Jyothsna Panchagnula
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Robert,

Thanks for the clarification!!!
Its helpful indeed.


-Jyothsna
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Glad that my explanation was helpful!
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever there is explicit downcasting one needs to makes sure if the Superclass ref_variable referencing to the Subclass object.

FYI.. Dog d = new Animal() is illegal..i.e in the above code one cant say as dog cannot behave like any other Animal.

so BB x = new AA(); is not legal for obvious reasons.
[ December 23, 2008: Message edited by: Himalay Majumdar ]
 
sudipto shekhar
Ranch Hand
Posts: 826
Chrome Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is-A test is the best to sort out this kind of problems.

Lion Is-A Animal
but Animal Is-A Lion?? No..so you cannot cast Animal to a Loin
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever there is explicit downcasting one needs to makes sure if the Superclass ref_variable referencing to the Subclass object.

But it's not necessary that the Superclass ref_variable references a Subclass object, it could also refer to an object of any of the Subclass' subclasses. The object it references simply needs to pass the Is-A test for the subclass type.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, thats right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic