May 25, 2023

A Dynamic and Scalable Zoo

GitHub

#Java

Cover image

Welcome to my project "Zoo", it is a small yet dynamic Java application designed I made for an internship opportunity. Despite its size, I take pride in crafting a system that is both dynamic and scalable. In this post, I'll delve into the architecture and design choice that make this zoo project unique.

Abstract Class Foundation

To lay the groundwork, I started by creating an abstract class called Animal. This class cannot be instantiated by itself, but it serves as a foundation for other classes to extend. The abstract class contains essential attributes like the animal's name and a greeting message.

1public abstract class Animal implements IAnimal { 2 private final String name; 3 private final String helloText; 4 5 public Animal(String name, String helloText) { 6 this.name = name; 7 this.helloText = helloText; 8 } 9 10 public void sayHello() { 11 System.out.println(helloText); 12 } 13 14 @Override 15 public String toString() { 16 return String.format("Hello my name is %s", this.name); 17 } 18}

Extending with Specialization

Given that a zoo primarily consists of various animals, extending the abstract class becomes straightforward. Let's take the example of a Lion class, which not only extends the Animal class but also implements the IEatMeat interface.

1public class Lion extends Animal implements IEatMeat { 2 public Lion(String name) { 3 super(name, "roooaoaaaaar"); 4 } 5 6 @Override 7 public void eatMeat() { 8 System.out.println("nomnomnom thx mate"); 9 } 10}

Interface Implementation and Retrieval

To enhance the dynamism of the system, I implemented a function called getAnimalsByInterface. This function takes a class object (interface) as a parameter and returns a list of all animals implementing that interface. For example, if we want a list of animals that eat meat, we would call this function with the IEatMeat interface.

1public <T> List<T> getAnimalsByInterface(Class<T> interfaceObj) { 2 List<T> animalsWithInterface = new ArrayList<>(); 3 4 for (Animal animal : animals.values()) { 5 if (interfaceObj.isInstance(animal)) { 6 animalsWithInterface.add(interfaceObj.cast(animal)); 7 } 8 } 9 10 return animalsWithInterface; 11}

This generic function ensures flexibility in obtaining animals based on specified interfaces, contributing to the overall adaptability of the zoo.

Conclusion

In conclusion, this small Java project showcases the power of abstraction, specialization, and dynamic retrieval. The design of the abstract class, interface implementation, and retrieval function allows for a scalable and extensible system. Whether you're dealing with lions that roar or animals with other specific dietary habits, this zoo application shows how versitile Java could be.