I am quite unsure here:
Image i=some image...
Bitmap B=(Bitmap)i;
The B now points to the same object as i. I am confused...I would say that Bitmap B will point to new instance of Image that is casted to bitmap but it is obviously not the case. Then I just do not get how it works here.
Yes an explicit cast creates a new object in the case of boxing, but its made behind the scenes by the compiler.
Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.
Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting. Before diving into the typecasting process, let's understand data types in Java.
Casting does not create a new object (at least, not unless new conversion operators have been defined, which is uncommon in non-numeric types, and doesn't apply in your example). It merely instructs the compiler how to "treat" an object. In the case you present, you're telling the compiler "don't worry, trust me, B
is actually a Bitmap
". If it turns out you've told it a fib, the runtime will catch you on it by throwing an InvalidCastException
at runtime.
MSDN has some more information.
A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur
A Dog is a specialised form of Animal. Dogs have dog-specific properties and behaviour (bark
, lickPrivateParts
) but also have the properties and behaviour common to all members of the group Animal (numberOfChromosomes
, breathe
, eat
etc.).
If you cast a Dog to Animal you are upcasting (treating a more specialised class as a less specialised base class). While cast to Animal the compiler/runtime will 'see' the Dog as a basic Animal and dog-specific properties and behaviour will not be available for this upcast dog-animal. This makes sense since, for example, a generic Animal will not 'bark'.
You are not creating a new Animal instance when you do this, rather you are using the Dog as if it was a less specialised Animal object.
Similarly, if you cast a Bitmap to an Image you will (for the duration of the time you're treating your Bitmap as an image) only be able to access the fields/properties of Image, not Bitmap.
One point to mention is that what you are doing in your example is downcasting (going from a less specialised to more specialised object). This is not always safe or sensible - if you think about it an instance of the Animal class doesn't have values or definition for the Dog-specific attributes.
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