黑马程序员技术交流社区
标题:
多态
[打印本页]
作者:
陈冬雪
时间:
2015-8-5 21:22
标题:
多态
/*
java.lang.ClassCastException:类型转换异常。
类型不匹配。
你存储的是Cat,想转换成Dog,肯定不行。
*/
class Animal
{
public void show()
{
System.out.println("show Animal");
}
}
class Cat extends Animal
{
public void show()
{
System.out.println("show Cat");
}
public void playGame()
{
System.out.println("捉迷藏");
}
}
class Dog extends Animal
{
public void show()
{
System.out.println("show Dog");//9.9.
}
}
class DuoTaiDemo4
{
public static void main(String[] args)
{
//多态
Animal a = new Dog(); //向上转型
a.show();
//给a重新赋值
a = new Cat(); //向上转型
a.show();
Cat c = (Cat)a; //向下转型
c.show();
c.playGame();
Dog d = (Dog)a;
d.show();
}
}
复制代码
作者:
塞巴斯的小夏尔
时间:
2015-8-5 21:23
赞一个!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2