I have an assignment that looks like this:
Write a class called
Animal
with a defaultsound()
method. Create child classes with thesound()
method for the following animals:pig, sheep, duck, cow.Create another class called
AnimalTest
that reads the command line user input and creates the appropriate Animal child class based on the type of animal, and then calls the animal’ssound()
method. Take some time to reflect on which class to create.
Do I write a test class that creates Animal
child classes? How do you create animal classes from the Test Class? YouTube isn't too helpful on this.
This is my code:
PARENT CLASS
public class Animal {
void animal() {
System.out.println("I am an animal");
}
public void sound() {
System.out.println("An animal makes a sound based on the animal that it is.");
}
public static void main(String[] args) {
Animal mypig = new Animal();
mypig.sound();
}
}
ONE OF FOUR CHILD CLASSES (others basically repeats)
public class cow extends Animal{
public cow() {
System.out.println("I am a cow");
}
public void sound() {
System.out.println("cow says “moo”");
}
}
MAIN CLASS
public class Main {
pig p = new pig();
sheep s = new sheep();
duck d = new duck();
cow c = new cow();
}
ANIMAL TEST CLASS
import java.util.Scanner;
public class AnimalTest {
//create main class
public static void main(String[] args) {
//create scanner
Scanner scan = new Scanner(System.in);
//get scanner input
String input = scan.nextLine();
}
}
I tried looking for test classes on YouTube but existing videos were only showing how to test existing classes.
AnimalTest is just a name your professor recommmended for the class that holds the main method (I believe there might have been some confusion, as you might have thought it was a special class type).
So, your Animal Test class should look something like this:
import java.util.Scanner;
public class AnimalTest{
public static void main(String[] args) {
Animal animal = null; // create an animal object
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.equals("pig")){ // assign a specific object instance based on the input
animal = new Pig();
}else if(input.equals("sheep")){
animal = new Sheep();
}else if(input.equals("cow")){
animal = new Cow();
}
animal.sound();
}
}
Your Animal class only needs the sound() method, which will be overrider by the child clases
class Animal {
void sound(){
System.out.println("Animal Sound");
}
}
Finally, your animal child classes should appear as follows (The @Override is an java annotation utilized when replacing method implementation from parent clases).
class Pig extends Animal{
@Override
void sound (){
System.out.println("Pig says oink !!");
}
}
If you found this answer useful, consider marking it as the accepted answer. Good luck.