java--多态2

public class PolyTest {

public static void main(String[] args) {

Cat cat = new Cat();

Animal animal = cat;//向上类型转换。子类转换成父类,不需要显式转换。

animal.sing();//这里输出为cat


Animal a = new Dog();
Dog dog =(Dog)a;//向下类型转换。也就是父类转换为子类,必须使用强制转换。

dog.sing();//这里输出为dog

Animal animal2 = new Animal();

Dog d = (Dog)animal2;//这里编译通过,运行报错,Animal cannot be cast to Dog.因为animal这个引用指向的是Animal这个对象,前面已经说过,多态可以说是父类的引用指向子类的对象,指向哪个对象就可以转换成哪个类型,

d.sing();




Animal b = new Cat();

Dog c = (Dog)b;

c.sing();//这里编译时没有错误,运行时会报错,Cat cannot be cast to Dog.子类不能转换成子类。

}
}
class Animal {
public void sing() {
System.out.println("animal");
}
}
class Dog extends Animal {
public void sing() {
System.out.println("dog");
}
}
class Cat extends Animal {
public void sing() {
System.out.println("cat");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值