Java object type conversion and forced object type conversion

Example 1

Animal:动物
Animal:可爱的动物
Cat:吃饭
Animal:动物在吃饭
Cat:可爱的小猫
Cat:猫喜欢吃鱼

Force object type conversion

animal.str = "";    // 编译出错,提示Animal类中没有str属性
animal.eatMethod();    // 编译出错,提示Animal类中没有eatMethod()方法
((Cat)animal).str = "";    // 编译成功
((Cat)animal).eatMethod();    // 编译成功
Cat cat = (Cat)animal;    // 编译成功,将Animal对象类型强制转换为Cat对象类型
Cat cat = new Cat();
Animal animal = cat;    // 向上转型,不必使用强制类型转换
Dog dog = new Dog();
Cat cat = (Cat)dog;    // 编译出错,不允许把Dog对象类型转换为Cat对象类型
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>