什么时候向上转型,向下转型,看这段代码:
abstract class Animal
{
abstract void eat();
}
class Cat extends Animal
{
public void eat()
{
System.out.println("吃鱼");
}
public void catchMouse()
{
System.out.println("抓老鼠");
}
}
class Dog extends Animal
{
public void eat()
{
System.out.println("吃骨头");
}
public void kanJia()
{
System.out.println("看家");
}
}
class DuoTaiDemo
{
public static void main(String[] args)
{Funtion f=new Funtion();
f.funtion(new Cat());
}
}
class Funtion
{
public void funtion(Animal a)//在这里f.funtion(new Cat());——》funtion(Animal a),就相当于完成了一次子类到父类的自动向上转换
{
a.eat();
if(a instanceof Cat)//instanceof(实例化属于)
{
Cat c=(Cat) a;//这里父类到子类的强制转换
c.catchMouse();
}
else if(a instanceof Dog)
{
Dog d=(Dog) a;
d.kanJia();
}
}
}
|