Does casting create new object?

后端 未结 4 761
别那么骄傲
别那么骄傲 2020-12-10 11:31

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 th

4条回答
  •  囚心锁ツ
    2020-12-10 12:04

    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.

提交回复
热议问题