abstract class Animal
{
public 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 Pig extends Animal
{
public void eat()
{
System.out.println("吃饲料");
}
public void gonDi()
{
System.out.println("拱地");
}
}
class DuoTaiDemo1
{
public static void main(String[] args)
{
function(new Cat());
function(new Dog());
function(new Pig());
}
public static void function(Animal a)//运用多态父类引用指向子
类对象
{
if(a instanceof Cat)
{
Cat c=(Cat)a;//强制向下转型,只能转父类引用不
能转对象。
c.catchMouse();
}
else if(a instanceof Dog)
{
Dog c=(Dog)a;
c.kanJia();
}
else if(a instanceof Pig)
{
Pig c=(Pig)a;
c.gonDi();
}
}
}
|
|