Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java cast anything?

I've taken a year of java course at school and my understanding of casting is pretty limited.

The type of casting I understand is casting int to double. This makes sense; 1 would become 1.0

The type of casting I don't quite understand is: casting a custom object (say superRectangle) to another customer object (eg, myRectangle). (this is assuming myRectangle is a subclass of superRectangle) What happens to all the private or public fields associated with an instance of superRectangle? How does the program know this is a legit move? For all that matters I could've just casted an int to a string, and what is that supposed to mean anyway?

like image 299
ampersands Avatar asked Dec 14 '22 22:12

ampersands


1 Answers

Strictly speaking, going from int to double isn't casting, but conversion. Casting is about reinterpreting the same, unchanged bit pattern in memory as belonging to another type. And this is precisely what casting reference types in Java boils down to: you have an object of some definite, unchangeable type, and you merely look at it as if it was an instance of one of its supertypes.

You will not be allowed to cast an Integer to a String because the latter is not the former's supertype. This is ensured at compile time and double-checked at runtime as well.

like image 72
Marko Topolnik Avatar answered Dec 29 '22 02:12

Marko Topolnik