From 18a1008901d3f3b06e8ca8fc077e065c420b8c63 Mon Sep 17 00:00:00 2001 From: Mike Chau Date: Tue, 5 Dec 2023 11:38:50 -0800 Subject: [PATCH] Make-up Assignment --- abstractclasses/Circle.java | 12 ++++ abstractclasses/Rectangle.java | 13 +++++ abstractclasses/Shape.java | 5 ++ anonymousclasses/AnimalShowcase.java | 43 +++++++++++++++ .../goodDesign/mainClasses/Circle.java | 43 +++++++++++++++ .../goodDesign/mainClasses/Rectangle.java | 37 +++++++++++++ .../goodDesign/mainInterfaces/Measurable.java | 5 ++ designpatterns/FacadeDesign.java | 50 +++++++++++++++++ .../dogWithExceptions/DogTrainer.java | 35 ++++++++++++ generics/GenericContainer.java | 33 +++++++++++ inheritance/InheritanceDemo.java | 39 +++++++++++++ interfaces/Music.java | 28 ++++++++++ interfaces/Playable.java | 5 ++ lambdaexpressions/Action.java | 5 ++ lambdaexpressions/LambdaExamples.java | 19 +++++++ multithreading/runnable/Counter.java | 33 +++++++++++ nestedclasses/OuterClass2.java | 31 +++++++++++ objectClass/clone/Car.java | 55 +++++++++++++++++++ polymorphism/PolymorphismDemo.java | 37 +++++++++++++ programmingContracts/Payment.java | 43 +++++++++++++++ programmingContracts/PaymentService.java | 7 +++ .../examples/depInversion/Application.java | 24 ++++++++ .../examples/depInversion/ConsoleLogger.java | 8 +++ .../examples/depInversion/FileLogger.java | 9 +++ .../examples/depInversion/Logger.java | 5 ++ swinggui/SwingApp.java | 31 +++++++++++ types/Zoo.java | 46 ++++++++++++++++ unitTests/src/StringHelper.java | 19 +++++++ unitTests/tests/StringHelperTest.java | 22 ++++++++ 29 files changed, 742 insertions(+) create mode 100644 abstractclasses/Circle.java create mode 100644 abstractclasses/Rectangle.java create mode 100644 abstractclasses/Shape.java create mode 100644 anonymousclasses/AnimalShowcase.java create mode 100644 designConsiderations/goodDesign/mainClasses/Circle.java create mode 100644 designConsiderations/goodDesign/mainClasses/Rectangle.java create mode 100644 designConsiderations/goodDesign/mainInterfaces/Measurable.java create mode 100644 designpatterns/FacadeDesign.java create mode 100644 exceptionhandling/dogWithExceptions/DogTrainer.java create mode 100644 generics/GenericContainer.java create mode 100644 inheritance/InheritanceDemo.java create mode 100644 interfaces/Music.java create mode 100644 interfaces/Playable.java create mode 100644 lambdaexpressions/Action.java create mode 100644 lambdaexpressions/LambdaExamples.java create mode 100644 multithreading/runnable/Counter.java create mode 100644 nestedclasses/OuterClass2.java create mode 100644 objectClass/clone/Car.java create mode 100644 polymorphism/PolymorphismDemo.java create mode 100644 programmingContracts/Payment.java create mode 100644 programmingContracts/PaymentService.java create mode 100644 solidprinciples/examples/depInversion/Application.java create mode 100644 solidprinciples/examples/depInversion/ConsoleLogger.java create mode 100644 solidprinciples/examples/depInversion/FileLogger.java create mode 100644 solidprinciples/examples/depInversion/Logger.java create mode 100644 swinggui/SwingApp.java create mode 100644 types/Zoo.java create mode 100644 unitTests/src/StringHelper.java create mode 100644 unitTests/tests/StringHelperTest.java diff --git a/abstractclasses/Circle.java b/abstractclasses/Circle.java new file mode 100644 index 0000000..3657c0d --- /dev/null +++ b/abstractclasses/Circle.java @@ -0,0 +1,12 @@ +package abstractclasses; + +public class Circle extends Shape{ + public void draw() { + System.out.println("Drawing Circle"); + } + + public static void main(String args[]) { + Shape circ = new Circle(); + circ.draw(); + } +} diff --git a/abstractclasses/Rectangle.java b/abstractclasses/Rectangle.java new file mode 100644 index 0000000..109d0c3 --- /dev/null +++ b/abstractclasses/Rectangle.java @@ -0,0 +1,13 @@ +package abstractclasses; + +public class Rectangle extends Shape { + @Override + public void draw() { + System.out.println("Drawing rectangle"); + } + + public static void main(String args[]) { + Shape rect = new Rectangle(); + rect.draw(); + } +} diff --git a/abstractclasses/Shape.java b/abstractclasses/Shape.java new file mode 100644 index 0000000..6a2437c --- /dev/null +++ b/abstractclasses/Shape.java @@ -0,0 +1,5 @@ +package abstractclasses; + +abstract class Shape { + abstract void draw(); +} diff --git a/anonymousclasses/AnimalShowcase.java b/anonymousclasses/AnimalShowcase.java new file mode 100644 index 0000000..45c3400 --- /dev/null +++ b/anonymousclasses/AnimalShowcase.java @@ -0,0 +1,43 @@ +package anonymousclasses; + +public class AnimalShowcase extends BirdClass implements BirdInterface, Pig { + public AnimalShowcase(String name) { + super(name); // Call the constructor of BirdClass + } + + // Implement the methods from the Pig interface + @Override + public void oink() { + System.out.println(getName() + " the bird-pig says: Oink!"); + } + + @Override + public void walk() { + System.out.println(getName() + " the bird-pig walks around happily."); + } + + // Override the chirp method from BirdClass to customize the behavior + @Override + public void chirp() { + System.out.println("Chirp chirp! I'm " + getName() + ", the unique bird-pig!"); + } + + // Override the fly method from BirdClass to customize the behavior + @Override + public void fly() { + System.out.println(getName() + " spreads its wings and flies!"); + } + + // Additional method to showcase the combined behaviors + public void showcaseAbilities() { + chirp(); + fly(); + oink(); + walk(); + } + + public static void main(String[] args) { + AnimalShowcase showcase = new AnimalShowcase("Mike"); + showcase.showcaseAbilities(); + } +} diff --git a/designConsiderations/goodDesign/mainClasses/Circle.java b/designConsiderations/goodDesign/mainClasses/Circle.java new file mode 100644 index 0000000..f220d32 --- /dev/null +++ b/designConsiderations/goodDesign/mainClasses/Circle.java @@ -0,0 +1,43 @@ +package designConsiderations.goodDesign.mainClasses; + +import designConsiderations.goodDesign.mainInterfaces.Measurable; + +// Good design because it utilizes interface to have the same method call to have different functionality depending on the object type. + +public class Circle implements Measurable { + private double radius; + + // Constructor to initialize the circle with a specific radius + public Circle(double radius) { + this.radius = radius; + } + + // Getter method for the radius + public double getRadius() { + return radius; + } + + // Setter method for the radius + public void setRadius(double radius) { + this.radius = radius; + } + + // Method to calculate the area of the circle + @Override + public double measureArea() { + return Math.PI * radius * radius; + } + + // Method to calculate the circumference of the circle + public double calculateCircumference() { + return 2 * Math.PI * radius; + } + + // Method to display the circle's details + public void displayDetails() { + System.out.println("Circle: "); + System.out.println("Radius: " + radius); + System.out.println("Area: " + measureArea()); + System.out.println("Circumference: " + calculateCircumference()); + } +} diff --git a/designConsiderations/goodDesign/mainClasses/Rectangle.java b/designConsiderations/goodDesign/mainClasses/Rectangle.java new file mode 100644 index 0000000..e5b0db1 --- /dev/null +++ b/designConsiderations/goodDesign/mainClasses/Rectangle.java @@ -0,0 +1,37 @@ +package designConsiderations.goodDesign.mainClasses; + +import designConsiderations.goodDesign.mainInterfaces.Measurable; + +public class Rectangle implements Measurable { + private double length; + private double width; + + // Constructor to initialize the rectangle + public Rectangle(double length, double width) { + this.length = length; + this.width = width; + } + + // Implementing the measure method to calculate area + @Override + public double measureArea() { + return length * width; + } + + // Getter and Setter methods + public double getLength() { + return length; + } + + public void setLength(double length) { + this.length = length; + } + + public double getWidth() { + return width; + } + + public void setWidth(double width) { + this.width = width; + } +} diff --git a/designConsiderations/goodDesign/mainInterfaces/Measurable.java b/designConsiderations/goodDesign/mainInterfaces/Measurable.java new file mode 100644 index 0000000..5611001 --- /dev/null +++ b/designConsiderations/goodDesign/mainInterfaces/Measurable.java @@ -0,0 +1,5 @@ +package designConsiderations.goodDesign.mainInterfaces; + +public interface Measurable { + double measureArea(); +} diff --git a/designpatterns/FacadeDesign.java b/designpatterns/FacadeDesign.java new file mode 100644 index 0000000..a17b829 --- /dev/null +++ b/designpatterns/FacadeDesign.java @@ -0,0 +1,50 @@ +package designpatterns; + + class SubsystemOne { + void operationOne() { + System.out.println("SubsystemOne: Operation One"); + } + + void operationTwo() { + System.out.println("SubsystemOne: Operation Two"); + } + } + + class SubsystemTwo { + void operationOne() { + System.out.println("SubsystemTwo: Operation One"); + } + + void operationTwo() { + System.out.println("SubsystemTwo: Operation Two"); + } + } + + class Facade { + private SubsystemOne subsystemOne; + private SubsystemTwo subsystemTwo; + + public Facade() { + subsystemOne = new SubsystemOne(); + subsystemTwo = new SubsystemTwo(); + } + + public void operationGroupOne() { + subsystemOne.operationOne(); + subsystemTwo.operationOne(); + } + + public void operationGroupTwo() { + subsystemOne.operationTwo(); + subsystemTwo.operationTwo(); + } + } + + public class FacadeDesign { + public static void main(String[] args) { + Facade facade = new Facade(); + + facade.operationGroupOne(); + facade.operationGroupTwo(); + } + } diff --git a/exceptionhandling/dogWithExceptions/DogTrainer.java b/exceptionhandling/dogWithExceptions/DogTrainer.java new file mode 100644 index 0000000..56b2196 --- /dev/null +++ b/exceptionhandling/dogWithExceptions/DogTrainer.java @@ -0,0 +1,35 @@ +package exceptionhandling.dogWithExceptions; + +public class DogTrainer { + // Method to train a dog and handle the exception + public void trainAndHandleException(Dog dog) { + try { + Dog trainedDog = trainDog(dog); + System.out.println("Successfully trained: " + trainedDog); + } catch (DogNotInitializedException error) { + System.err.println("Error while training the dog: " + error.getMessage()); + } + } + + // Method to train a dog, potentially throwing an exception + public Dog trainDog(Dog traineeDog) throws DogNotInitializedException { + if (traineeDog != null) { + traineeDog.setCanShakeHands(true); + return traineeDog; + } else { + throw new DogNotInitializedException("Trainee Dog was not initialized!"); + } + } + + public static void main(String[] args) { + DogTrainer trainer = new DogTrainer(); + + // Example with a properly initialized dog + Dog buddy = new Dog("Mike", 5); + trainer.trainAndHandleException(buddy); + + // Example with a null dog + Dog unknownDog = null; + trainer.trainAndHandleException(unknownDog); + } +} diff --git a/generics/GenericContainer.java b/generics/GenericContainer.java new file mode 100644 index 0000000..095b76e --- /dev/null +++ b/generics/GenericContainer.java @@ -0,0 +1,33 @@ +package generics; + +public class GenericContainer { + private T object; + + public GenericContainer(T object) { + this.object = object; + } + + public void setObject(T object) { + this.object = object; + } + + public T getObject() { + return object; + } + + public static void main(String[] args) { + // Example usage of GenericContainer with different types + + // Integer container + GenericContainer intContainer = new GenericContainer<>(123); + System.out.println("Integer Value: " + intContainer.getObject()); + + // String container + GenericContainer stringContainer = new GenericContainer<>("a"); + System.out.println("String Value: " + stringContainer.getObject()); + + // Double container + GenericContainer doubleContainer = new GenericContainer<>(9.99); + System.out.println("Double Value: " + doubleContainer.getObject()); + } +} \ No newline at end of file diff --git a/inheritance/InheritanceDemo.java b/inheritance/InheritanceDemo.java new file mode 100644 index 0000000..99809d5 --- /dev/null +++ b/inheritance/InheritanceDemo.java @@ -0,0 +1,39 @@ +package inheritance; + +class Vehicle { + private String make; + private String model; + + public Vehicle(String make, String model) { + this.make = make; + this.model = model; + } + + public void displayInfo() { + System.out.println("Vehicle Make: " + make + ", Model: " + model); + } +} + +// Subclass +class Car extends Vehicle { + private int numberOfDoors; + + public Car(String make, String model, int numberOfDoors) { + super(make, model); // Calling the constructor of the superclass + this.numberOfDoors = numberOfDoors; + } + + public void displayCarInfo() { + // This method extends the functionality of the superclass + super.displayInfo(); // Calling the method from the superclass + System.out.println("Number of Doors: " + numberOfDoors); + } +} + +// Main class to demonstrate inheritance +public class InheritanceDemo { + public static void main(String[] args) { + Car car = new Car("Toyota", "Camry", 4); + car.displayCarInfo(); // Displays information about the car + } +} diff --git a/interfaces/Music.java b/interfaces/Music.java new file mode 100644 index 0000000..aba848b --- /dev/null +++ b/interfaces/Music.java @@ -0,0 +1,28 @@ +package interfaces; + +// First class implementing the interface +class Guitar implements Playable { + @Override + public void play() { + System.out.println("Playing the guitar."); + } +} + +// Second class implementing the interface +class Piano implements Playable { + @Override + public void play() { + System.out.println("Playing the piano."); + } +} + +// Main class to demonstrate the use of the interface +public class Music { + public static void main(String[] args) { + Playable guitar = new Guitar(); + Playable piano = new Piano(); + + guitar.play(); // Outputs: Playing the guitar. + piano.play(); // Outputs: Playing the piano. + } +} diff --git a/interfaces/Playable.java b/interfaces/Playable.java new file mode 100644 index 0000000..540e0f5 --- /dev/null +++ b/interfaces/Playable.java @@ -0,0 +1,5 @@ +package interfaces; + +public interface Playable { + void play(); +} diff --git a/lambdaexpressions/Action.java b/lambdaexpressions/Action.java new file mode 100644 index 0000000..3693690 --- /dev/null +++ b/lambdaexpressions/Action.java @@ -0,0 +1,5 @@ +package lambdaexpressions; + +public interface Action { + void perform(); +} diff --git a/lambdaexpressions/LambdaExamples.java b/lambdaexpressions/LambdaExamples.java new file mode 100644 index 0000000..8fd6965 --- /dev/null +++ b/lambdaexpressions/LambdaExamples.java @@ -0,0 +1,19 @@ +package lambdaexpressions; + +public class LambdaExamples { + public static void main(String[] args) { + // Lambda expression for a greeting action + Action greet = () -> System.out.println("Hello, world!"); + + // Lambda expression for a task completion action + Action completeTask = () -> System.out.println("Task completed successfully!"); + + // Performing the actions + performAction(greet); + performAction(completeTask); + } + + private static void performAction(Action action) { + action.perform(); + } +} diff --git a/multithreading/runnable/Counter.java b/multithreading/runnable/Counter.java new file mode 100644 index 0000000..87f2334 --- /dev/null +++ b/multithreading/runnable/Counter.java @@ -0,0 +1,33 @@ +package multithreading.runnable; + +public class Counter implements Runnable { + private int count = 0; + + @Override + public void run() { + // This method is executed when the thread starts + for (int i = 0; i < 5; i++) { + count++; + System.out.println(Thread.currentThread().getName() + " incremented count to: " + count); + + // Adding a small delay for demonstration purposes + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + System.out.println(Thread.currentThread().getName() + " was interrupted"); + } + } + } + + public static void main(String[] args) { + Counter counter = new Counter(); + + // Creating two threads that run the same instance of Counter + Thread thread1 = new Thread(counter, "Thread 1"); + Thread thread2 = new Thread(counter, "Thread 2"); + + // Starting both threads + thread1.start(); + thread2.start(); + } +} \ No newline at end of file diff --git a/nestedclasses/OuterClass2.java b/nestedclasses/OuterClass2.java new file mode 100644 index 0000000..2146d9b --- /dev/null +++ b/nestedclasses/OuterClass2.java @@ -0,0 +1,31 @@ +package nestedclasses; + +public class OuterClass2 { + private static String staticMessage = "I am a static nested class."; + private String nonStaticMessage = "I am an inner class."; + + // Static nested class + static class StaticNestedClass { + void display() { + System.out.println(staticMessage); // Can access static members of the outer class + } + } + + // Inner class + class InnerClass { + void display() { + System.out.println(nonStaticMessage); // Can access non-static members of the outer class + } + } + + public static void main(String[] args) { + // Creating an instance of the static nested class + OuterClass2.StaticNestedClass nestedObject = new OuterClass2.StaticNestedClass(); + nestedObject.display(); + + // Creating an instance of the inner class + OuterClass2 outerObject = new OuterClass2(); + OuterClass2.InnerClass innerObject = outerObject.new InnerClass(); + innerObject.display(); + } +} \ No newline at end of file diff --git a/objectClass/clone/Car.java b/objectClass/clone/Car.java new file mode 100644 index 0000000..81db8bd --- /dev/null +++ b/objectClass/clone/Car.java @@ -0,0 +1,55 @@ +package objectClass.clone; + +public class Car implements Cloneable { + private String brand; + private int year; + + public Car(String brand, int year) { + this.brand = brand; + this.year = year; + } + + // Getter and setter for the brand field + public String getBrand() { + return brand; + } + + public void setBrand(String brand) { + this.brand = brand; + } + + // Getter and setter for the year field + public int getYear() { + return year; + } + + public void setYear(int year) { + this.year = year; + } + + // Overriding the clone method for shallow copy + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + @Override + public String toString() { + return "Car{" + + "brand='" + brand + '\'' + + ", year=" + year + + '}'; + } + + public static void main(String[] args) { + try { + Car originalCar = new Car("Toyota", 2021); + Car clonedCar = (Car) originalCar.clone(); // Cloning the Car object + + System.out.println("Original Car: " + originalCar); + System.out.println("Cloned Car: " + clonedCar); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + } +} diff --git a/polymorphism/PolymorphismDemo.java b/polymorphism/PolymorphismDemo.java new file mode 100644 index 0000000..7120709 --- /dev/null +++ b/polymorphism/PolymorphismDemo.java @@ -0,0 +1,37 @@ +package polymorphism; + +class Animal { + void makeSound() { + System.out.println("Some sound"); + } +} + +// Subclass 1 +class Dog extends Animal { + @Override + void makeSound() { + System.out.println("Bark"); + } +} + +// Subclass 2 +class Cat extends Animal { + @Override + void makeSound() { + System.out.println("Meow"); + } +} + +// Main class to demonstrate polymorphism +public class PolymorphismDemo { + public static void main(String[] args) { + Animal myAnimal; + + // Polymorphism in action + myAnimal = new Dog(); + myAnimal.makeSound(); // Outputs: Bark because we used the dog object + + myAnimal = new Cat(); + myAnimal.makeSound(); // Outputs: Meow because we used the cat object + } +} diff --git a/programmingContracts/Payment.java b/programmingContracts/Payment.java new file mode 100644 index 0000000..947e71f --- /dev/null +++ b/programmingContracts/Payment.java @@ -0,0 +1,43 @@ +package programmingContracts; + +// Class implementing the contract +class CreditCardPaymentService implements PaymentService { + private double balance; + private String credentials; + + @Override + public boolean processPayment(double amount) { + if (amount <= balance) { + balance -= amount; + System.out.println("Payment processed: " + amount); + return true; + } else { + System.out.println("Insufficient balance to process payment."); + return false; + } + } + + @Override + public double getBalance() { + return balance; + } + + @Override + public void setCredentials(String credentials) { + this.credentials = credentials; + // Assume some logic to initialize the balance based on credentials + balance = 1000.0; // This is just an example value + } +} + +// Main class to demonstrate the use of the contract +public class Payment { + public static void main(String[] args) { + PaymentService paymentService = new CreditCardPaymentService(); + paymentService.setCredentials("user:password"); + + System.out.println("Initial Balance: " + paymentService.getBalance()); + paymentService.processPayment(500); + System.out.println("Balance after transaction: " + paymentService.getBalance()); + } +} diff --git a/programmingContracts/PaymentService.java b/programmingContracts/PaymentService.java new file mode 100644 index 0000000..2d03b40 --- /dev/null +++ b/programmingContracts/PaymentService.java @@ -0,0 +1,7 @@ +package programmingContracts; + +public interface PaymentService { + boolean processPayment(double amount); + double getBalance(); + void setCredentials(String credentials); +} diff --git a/solidprinciples/examples/depInversion/Application.java b/solidprinciples/examples/depInversion/Application.java new file mode 100644 index 0000000..e0d9589 --- /dev/null +++ b/solidprinciples/examples/depInversion/Application.java @@ -0,0 +1,24 @@ +package solidprinciples.examples.depInversion; + +public class Application { + private Logger logger; + + // Constructor injection for dependency + public Application(Logger logger) { + this.logger = logger; + } + + public void process(String data) { + // Some processing logic + logger.log("Data processed: " + data); + } + + public static void main(String[] args) { + // Dependency is being injected from outside + Application app1 = new Application(new ConsoleLogger()); + app1.process("Some data for ConsoleLogger"); + + Application app2 = new Application(new FileLogger()); + app2.process("Some data for FileLogger"); + } +} diff --git a/solidprinciples/examples/depInversion/ConsoleLogger.java b/solidprinciples/examples/depInversion/ConsoleLogger.java new file mode 100644 index 0000000..d6169e1 --- /dev/null +++ b/solidprinciples/examples/depInversion/ConsoleLogger.java @@ -0,0 +1,8 @@ +package solidprinciples.examples.depInversion; + +public class ConsoleLogger implements Logger { + @Override + public void log(String message) { + System.out.println("ConsoleLogger: " + message); + } +} diff --git a/solidprinciples/examples/depInversion/FileLogger.java b/solidprinciples/examples/depInversion/FileLogger.java new file mode 100644 index 0000000..c6206dd --- /dev/null +++ b/solidprinciples/examples/depInversion/FileLogger.java @@ -0,0 +1,9 @@ +package solidprinciples.examples.depInversion; + +public class FileLogger implements Logger { + @Override + public void log(String message) { + // Logic to write the message to a file + System.out.println("FileLogger: " + message); + } +} diff --git a/solidprinciples/examples/depInversion/Logger.java b/solidprinciples/examples/depInversion/Logger.java new file mode 100644 index 0000000..9359c2c --- /dev/null +++ b/solidprinciples/examples/depInversion/Logger.java @@ -0,0 +1,5 @@ +package solidprinciples.examples.depInversion; + +public interface Logger { + void log(String message); +} diff --git a/swinggui/SwingApp.java b/swinggui/SwingApp.java new file mode 100644 index 0000000..bd3056f --- /dev/null +++ b/swinggui/SwingApp.java @@ -0,0 +1,31 @@ +package swinggui; + +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.SwingUtilities; + +public class SwingApp { + // Method to create and show the GUI + private static void createAndShowGUI() { + // Creating the window (JFrame) + JFrame frame = new JFrame("Basic Swing App"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + // Adding a text label (JLabel) + JLabel label = new JLabel("Hello, World!"); + frame.getContentPane().add(label); + + // Setting the frame size and making it visible + frame.setSize(300, 200); + frame.setVisible(true); + } + + public static void main(String[] args) { + // Ensuring GUI creation is done in the Event Dispatch Thread + SwingUtilities.invokeLater(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + } +} diff --git a/types/Zoo.java b/types/Zoo.java new file mode 100644 index 0000000..7d19ed0 --- /dev/null +++ b/types/Zoo.java @@ -0,0 +1,46 @@ +package types; + +import java.util.ArrayList; +import java.util.List; + +public class Zoo { + + // List to store animals of type Animal + private List animals; + + // Constructor to initialize the list + public Zoo() { + animals = new ArrayList<>(); + } + + // Method to add an animal to the zoo + public void addAnimal(Animal animal) { + animals.add(animal); + } + + // Method to make each animal in the zoo make its sound + public void makeAnimalsSound() { + // Loop through each animal in the list + for (Animal animal : animals) { + // Call the sound method of each animal + animal.sound(); + + // Check the type of the animal using instanceof + // and call the specific methods for Dog and Cat + if (animal instanceof Dog) { + ((Dog) animal).bark(); // Cast to Dog and call bark method + } else if (animal instanceof Cat) { + ((Cat) animal).meow(); // Cast to Cat and call meow method + } + } + } + + // Main method to demonstrate the usage of the Zoo class + public static void main(String[] args) { + Zoo zoo = new Zoo(); // Create a new Zoo instance + zoo.addAnimal(new Dog()); // Add a Dog to the zoo + zoo.addAnimal(new Cat()); // Add a Cat to the zoo + + zoo.makeAnimalsSound(); // Make all animals in the zoo make their sound + } +} \ No newline at end of file diff --git a/unitTests/src/StringHelper.java b/unitTests/src/StringHelper.java new file mode 100644 index 0000000..1ae137a --- /dev/null +++ b/unitTests/src/StringHelper.java @@ -0,0 +1,19 @@ +package unitTests.src; + +public class StringHelper { + // Method to reverse a string + public String reverse(String input) { + if (input == null) { + return null; + } + return new StringBuilder(input).reverse().toString(); + } + + // Method to capitalize a string + public String capitalize(String input) { + if (input == null || input.isEmpty()) { + return input; + } + return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase(); + } +} diff --git a/unitTests/tests/StringHelperTest.java b/unitTests/tests/StringHelperTest.java new file mode 100644 index 0000000..3f6de4c --- /dev/null +++ b/unitTests/tests/StringHelperTest.java @@ -0,0 +1,22 @@ +package unitTests.tests; + +import org.junit.*; +import unitTests.src.StringHelper; + +public class StringHelperTest { + @Test + public void testReverse() { + StringHelper utility = new StringHelper(); + Assert.assertNull("Reverse of null should be null", utility.reverse(null)); + Assert.assertEquals("Reverse of empty string should be empty", "", utility.reverse("")); + Assert.assertEquals("Reverse of 'abc' should be 'cba'", "cba", utility.reverse("abc")); + } + + @Test + public void testCapitalize() { + StringHelper utility = new StringHelper(); + Assert.assertNull("Capitalize of null should be null", utility.capitalize(null)); + Assert.assertEquals("Capitalize of empty string should be empty", "", utility.capitalize("")); + Assert.assertEquals("Capitalize of 'hello' should be 'Hello'", "Hello", utility.capitalize("hello")); + } +}