本帖最后由 Jim-剣◆﹏ 于 2013-10-19 00:02 编辑
- abstract class Animla
- {
- String type;
- Animla()
- {}
- Animla(String type)
- {
- this.type = type;
- }
- public abstract void move();
- }
- class Fish extends Animla
- {
- Fish(String type)
- {
- super(type);
- }
- public void move()
- {
- sop("鱼儿游动");
- }
- public void fishEat()
- {
- sop("鱼儿吃饲料");
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class Snake extends Animla
- {
- Snake(String type)
- {
- super(type);
- }
- public void move()
- {
- sop("蛇爬行");
- }
- public void snakeEat()
- {
- sop("吃老鼠");
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class TestDemo33
- {
- public static void main(String[] args)
- {
- Animal an = new Snake("蛇");
- acceptAnimal(an);
- }
- public static void acceptAnimal(Animal an)
- {
- /*父类引用接收子类对象,如果直接调用子类特有方法,编译会不通过
-
- */
- if(an instanceof Snake)
- {
- Snake sn = (Snake)an;
- sn.snakeEat();
- }
- else if(an instanceof Fish)
- {
- Fish fs = (Fish)an;
- fs.fishEat();
- }
- else
- return ;
- }
- }
复制代码 我查了书,多态发生向下转型时必须首先发生向上转型,代码中Animla是父类,Fish和Snake是子类,在主函数中,Animal an = new Snake("蛇");发生了向上转型,acceptAnimal(an);调用函数用instanceof判断,为什么编译还是不通过
错误提示为:
TestDemo33.java:65: 错误: 不兼容的类型
Animal an = new Snake("蛇");
^
需要: Animal
找到: Snake
TestDemo33.java:73: 错误: 不可转换的类型
if(an instanceof Snake)
^
需要: Snake
找到: Animal
TestDemo33.java:75: 错误: 不可转换的类型
Snake sn = (Snake)an;//
^
需要: Snake
找到: Animal
TestDemo33.java:78: 错误: 不可转换的类型
else if(an instanceof Fish)
^
需要: Fish
找到: Animal
TestDemo33.java:80: 错误: 不可转换的类型
Fish fs = (Fish)an;
^
需要: Fish
找到: Animal
5 个错误
是不是因为父类是抽象类的缘故?
|