In: Computer Science
In Java
Animal.java
public class Animal {
private String animalType, animalName, cageType, animalFood;
public Animal()
{
this.animalType = "";
this.animalName = "";
this.cageType = "";
this.animalFood = "";
}
public Animal(String animalType, String animalName, String
cageType, String animalFood)
{
this.animalType = animalType;
this.animalName = animalName;
this.cageType = cageType;
this.animalFood = animalFood;
}
public String getAnimalType() {
return animalType;
}
public void setAnimalType(String animalType) {
this.animalType = animalType;
}
public String getAnimalName() {
return animalName;
}
public void setAnimalName(String animalName) {
this.animalName = animalName;
}
public String getCageType() {
return cageType;
}
public void setCageType(String cageType) {
this.cageType = cageType;
}
public String getAnimalFood() {
return animalFood;
}
public void setAnimalFood(String animalFood) {
this.animalFood = animalFood;
}
@Override
public String toString()
{
return ("I am " + this.animalName + " the " + this.animalType
+ " and I live in cage " + this.cageType + ". I eat " +
this.animalFood + ".");
}
}
Zoo.java
public class Zoo {
private Animal animal[];
private int size;
private static int count = 0;
public Zoo()
{
this.size = 3;
this.animal = new Animal[size];
}
public void addAnimal(Animal animal)
{
if(count == size)
throw new ArrayIndexOutOfBoundsException("Cannot add more than 3
animals!");
else
this.animal[count++] = animal;
}
public void printAnimalDetails()
{
for(int i = 0; i < animal.length; i++)
{
System.out.println(animal[i].toString());
}
System.out.println();
}
}
TestZoo.java
public class TestZoo {
public static void main(String[] args)
{
Zoo zoo = new Zoo();
try
{
Animal lion = new Animal("lion", "Laila", "1", "fresh meat");
Animal hawk = new Animal("hawk", "Hahn", "2", "rodents");
Animal deer = new Animal("deer", "Deepak", "2", "fresh
grass");
zoo.addAnimal(lion);
zoo.addAnimal(hawk);
zoo.addAnimal(deer);
zoo.printAnimalDetails();
}catch(ArrayIndexOutOfBoundsException aio){
System.out.println(aio.getMessage());
}
}
}
**********************************************************************************************************************************************
SCREENSHOT:
UML Diagram:
Explanation: The relation between the two classes is Composition; the Zoo class is composed of the Animal class. If the Zoo does not exist, the Animals will also cease to exist. In other words, the existence of the Animal class depends on the life cycle of the Zoo class.