abstract class Animal extends Object{
String type = "";
public Animal(){
setType();
}
public abstract void setType();
public abstract String getType();
}
class Giraffe extends Animal{
public void setType(){
type = "Giraffe";
}
public String getType(){
return type;
}
}
class Cheetah extends Animal{
public void setType(){
type = "Cheetah";
}
public String getType(){
return type;
}
}
class Gazelle extends Animal{
public void setType(){
type = "Gazelle";
}
public String getType(){
return type;
}
}
public class Test{
public static void main(String[] args){
(new Test()).test();
}
public void test(){
Animal[] animals = new Animal[10];
animals[0] = (Animal)new Giraffe();
animals[1] = new Cheetah();
animals[2] = new Gazelle();
animals[3] = new Giraffe();
animals[4] = new Cheetah();
animals[5] = new Gazelle();
animals[6] = new Cheetah();
animals[7] = new Cheetah();
animals[8] = new Giraffe();
for (int i = 0; i < animals.length;i++){
if (animals[i] == null) {
System.out.println("Not initialized.");
} else{
if (animals[i] instanceof
Giraffe) System.out.println("animals[" + i + "] is a Giraffe");
if (animals[i] instanceof
Cheetah) System.out.println("animals[" + i + "] is a Cheetah");
if (animals[i] instanceof
Gazelle) System.out.println("animals[" + i + "] is a Gazelle");
if (animals[i] instanceof Cheetah)
System.out.println("animals[" + i + "] is an Animal");
}
}
}
}