How to downcast a Java object?

前端 未结 4 1847
时光取名叫无心
时光取名叫无心 2020-12-24 07:54

I am trying to understand Java\'s polymorphism, and I have one question about downcasting an object. Let\'s say for this example I have two subclasses Dog and Cat that inher

4条回答
  •  春和景丽
    2020-12-24 08:35

    You should only cast to a class that the object really is, so if you have a Dog that extends Animal you can cast it to an Animal (because it is one) but you shouldn't cast an Animal to a Dog because not all Animals are Dogs. The Dog class may well have extra fields that are not implemented by the Animal class and so the cast doesn't make sense (what do you initialise those values to?).

提交回复
热议问题