public class ArrayTest{
public static void main(String[] args)
{
Animal[] a=new Animal[3];
Dog d1=new Dog();
Dog d2=new Dog();
Cat c1=new Cat();
Cat c2=new Cat();
a[0]=d1;
a[1]=d2;
a[2]=c1;
a[3]=c2;
//需求:遍历数组,取出每一个对象,如果是Dog,执行eat方法,如果是Cat,执行move方法。
for(int i=0;i<a.length;i++)
{
Animal an = a[i];
if( an instanceof Dog){
Dog d = (Dog)an;
d.eat();
}else if(an instanceof Cat){
Cat c=(Cat)an;
c.move();
}
}
}
}
//定义了动物类,狗类,猫类
class Animal{
}
class Dog extends Animal{
public void eat(){
System.out.println("Dog eat!");
}
}
class Cat extends Animal{
public void move(){
System.out.println("Dog move!");
}
}
转载于:https://blog.51cto.com/hangtiangazi/1661766