Skip to content

Mini Project – Exercise 4

Using OOP for pets

  • Project
  • 1 hint
  • 6 of 9 in this chapter

Objective

Create a program that has one dog object that is made from the dog class. The dog class must inherit methods and attributes from an ‘animal’ class. You must create two getter functions to get attributes, and one setter function for the animal class. The dog class must have two methods , one to make noise and one to exercise. You will need to implement the scanner function to ask the user to do things.

Here is what the output will look like...

Java
Enter a command: Set name, Get eyes, Get legs, exercise, make noise, or stop to stop: 
get eyes
your pet has 2 eyes!
Enter a command: Set name, Get eyes, Get legs, exercise, make noise, or stop to stop: 
get legs
your pet has 4 legs!
Enter a command: Set name, Get eyes, Get legs, exercise, make noise, or stop to stop: 
exercise
The dog does for a walk
Enter a command: Set name, Get eyes, Get legs, exercise, make noise, or stop to stop: 
a command
That is not an option, try again
Enter a command: Set name, Get eyes, Get legs, exercise, make noise, or stop to stop: 
make noise
The dog says woof
Enter a command: Set name, Get eyes, Get legs, exercise, make noise, or stop to stop: 
stop

Hints

Hint 1X

X

Solution

Solution – Exercise 4

Here is one solution:

Java
import java.util.Scanner;
class animal{
 int legs = 4;
 int eyes = 2;
 String name = "";
 void setName(String petName){
 name = petName;
 System.out.println("That pets name is now: " + petName);
 }
 int getEyes(){
 return eyes;
 }
 int getLegs(){
 return legs;
 }
}
class theDog extends animal{
 void makeNoise(){
 System.out.println("The dog says woof");
 }
 void exercise(){
 System.out.println("The dog does for a walk");
 }
}
public class AnimalExample {
 public static void main(String[] args) {
 Scanner input = new Scanner(System.in);
 String userInput ="";
 theDog pet = new theDog();

 while(!userInput.equalsIgnoreCase("stop")){
 System.out.println("Enter a command: Set name, Get eyes, Get legs, exercise, make noise, or stop to stop: ");
 userInput = input.nextLine();
 if(userInput.equalsIgnoreCase("Set name")){
 System.out.println("Set a name for your pet: ");
 String thepetName = input.nextLine();
 pet.setName(thepetName);
 }
 else if(userInput.equalsIgnoreCase("get eyes")){
 int numberOfEyes= pet.getEyes();
 System.out.println("your pet has " + numberOfEyes + " eyes!");
 }
 else if(userInput.equalsIgnoreCase("get legs")){
 int numberOfLegs = pet.getLegs();
 System.out.println("your pet has " + numberOfLegs + " legs!");
 }
 else if(userInput.equalsIgnoreCase("exercise")){
 pet.exercise();
 }
 else if(userInput.equalsIgnoreCase("make noise")){
 pet.makeNoise();
 }
 else{
 if(!userInput.equalsIgnoreCase("stop")){
 System.out.println("That is not an option, try again");
 }
 }
 }
 input.close();
 }
} 

Give the project a try first.