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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With