• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Referene Variable Casting

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I have a doubt in reference variable casting.

Assume Dog extends Animal.

1) Is it true that the second statement will compile but not run:


In other words is it safe to believe that, whenever we are down-casting, the program will always compile but never run?

2)

For up-casting is it safe to believe that, it will always compile and run fine.
Are there any special cases where up-casting can cause compilation or run problems?

Thanks

Regards,
Badal Chowdhary
 
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you tried running the statement?
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
2) true
1) when Animal a = new Dog(); it runs.



Originally posted by Badal Chowdhary:
Hi All,

I have a doubt in reference variable casting.

Assume Dog extends Animal.

1) Is it true that the second statement will compile but not run:


In other words is it safe to believe that, whenever we are down-casting, the program will always compile but never run?

2)

For up-casting is it safe to believe that, it will always compile and run fine.
Are there any special cases where up-casting can cause compilation or run problems?

Thanks

Regards,
Badal Chowdhary

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

you can think of cases where down-casting does not cause any runtime exceptions like the one below:
( suppose class Dog extends Animal )

so this is not a rule that down-casting ends up with a runtime problem.
Regards,
Paul.
 
Who knew that furniture could be so violent? Put this tiny ad out there to see what happens:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic