aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Referene Variable Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Referene Variable Casting" Watch "Referene Variable Casting" New topic
Author

Referene Variable Casting

George Gates
Ranch Hand

Joined: Jul 11, 2008
Posts: 34
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


Regards,<br />George Gates
Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
Have you tried running the statement?


The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Ben Smither
Greenhorn

Joined: Sep 09, 2008
Posts: 4
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
Paul Prusko
Greenhorn

Joined: Feb 16, 2008
Posts: 25
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Referene Variable Casting
 
Similar Threads
casting object references.
Polymorphism
I've looked through the threads on casting to try to get my head wrapped around it.
down casting