In this code-along, you'll create a polymorphic Zoo application that demonstrates key concepts of interfaces and polymorphism. You'll build a system that manages different types of animals using a common interface.
// Animal interface defining behaviors all animals must implement public interface Animal { String getName(); String makeSound(); String eat(); } // Lion class implementing the Animal interface public class Lion implements Animal { private String name; public Lion(String name) { this.name = name; } @Override public String getName() { return name; } @Override public String makeSound() { return "ROAR!"; } @Override public String eat() { return name + " is eating meat"; } } // Zoo class manages a collection of different animal types public class Zoo { private Listanimals = new ArrayList<>(); public void addAnimal(Animal animal) { animals.add(animal); } public void makeAllSounds() { for (Animal animal : animals) { // Polymorphic method call - different behavior based on animal type System.out.println(animal.getName() + " says: " + animal.makeSound()); } } }
In this code-along, you'll build a Prime Recommender application that uses Java generics to create flexible data structures. This project demonstrates how to implement generic classes and methods to handle different types of data.
// Generic class with type parameter T public class Recommender{ private List items = new ArrayList<>(); public void addItem(T item) { items.add(item); } // Generic method with its own type parameter public List filterByType(Class type) { List result = new ArrayList<>(); for (T item : items) { if (type.isInstance(item)) { result.add(type.cast(item)); } } return result; } // Method using bounded type parameter public double calculateAverage(List numbers) { if (numbers.isEmpty()) { return 0.0; } double sum = 0.0; for (N number : numbers) { sum += number.doubleValue(); } return sum / numbers.size(); } } // Using the generic class public class PrimeRecommenderDemo { public static void main(String[] args) { // Create a recommender for movies Recommender movieRecommender = new Recommender<>(); movieRecommender.addItem(new Movie("The Matrix", 8.7)); movieRecommender.addItem(new Movie("Inception", 8.8)); // Create a recommender for books Recommender bookRecommender = new Recommender<>(); bookRecommender.addItem(new Book("1984", "George Orwell")); // Both use the same Recommender class with different types } }