Showcasing Simple Implementation of Interfaces With Animals

master
Hammy 4 years ago
parent 6dc0b549f6
commit e2ca162fa0

@ -0,0 +1,9 @@
package src;
public interface Animal {
String animalName();
String animalSound();
double animalPrice();
}

@ -0,0 +1,38 @@
package src;
public class AnimalHelper {
private final Animal[] animals;
private double averagePrice;
public AnimalHelper(Animal[] animals) {
this.animals = animals;
}
public void displayInformation() {
/* Display the animal information */
int total = 0;
double sum = 0.0;
for (Animal animal : animals) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n\nName: " + animal.animalName());
stringBuilder.append("\nSound: " + animal.animalSound());
stringBuilder.append("\nPrice: £" + animal.animalPrice());
System.out.println(stringBuilder.toString());
total++;
sum += animal.animalPrice();
}
averagePrice = sum / total;
}
public void displayAveragePrice() {
/* Display the average price of all the animals */
System.out.printf("\nThe Average Price For All The Animals Are: £%.2f", averagePrice);
}
}

@ -0,0 +1,22 @@
package src;
public class AnimalMain {
public static void main(String[] args) {
displayAnimals();
}
private static void displayAnimals() {
// Creating an array of animal objects
AnimalHelper helper = new AnimalHelper(new Animal[] {
new Cow(),
new Cat(),
new Dog(),
new Horse()
});
// Displaying information about the animals
helper.displayInformation();
helper.displayAveragePrice();
}
}

@ -0,0 +1,20 @@
package src;
public class Cat implements Animal {
@Override
public String animalName() {
return "Cat";
}
@Override
public String animalSound() {
return "Meoooww";
}
@Override
public double animalPrice() {
return 29.99;
}
}

@ -0,0 +1,20 @@
package src;
public class Cow implements Animal {
@Override
public String animalName() {
return "Cow";
}
@Override
public String animalSound() {
return "Moooo";
}
@Override
public double animalPrice() {
return 10.99;
}
}

@ -0,0 +1,20 @@
package src;
public class Dog implements Animal {
@Override
public String animalName() {
return "Dog";
}
@Override
public String animalSound() {
return "Woof Woof";
}
@Override
public double animalPrice() {
return 15.99;
}
}

@ -0,0 +1,20 @@
package src;
public class Horse implements Animal {
@Override
public String animalName() {
return "Horse";
}
@Override
public String animalSound() {
return "Neighh";
}
@Override
public double animalPrice() {
return 59.99;
}
}
Loading…
Cancel
Save