Answer to Question #178905 in Java | JSP | JSF for pet class

Question #178905
  1. Write a class named Pet, which should have the following fields:
  • name, The name field holds the name of a pet
  • The animal field holds the type of animal that a pet is Example values are”Dog”,”Cat”, and “Bird”.
  • The age field holds the pet’s age.

           The Pet class should also have the following methods:

  • The setName method stores a value in the name field.
  • The setAnimal method stores a value in the animal field
  • The setAge method stores a value in the age field.
  • The getName method returns value of the name field
  • The getAnimal method returns the value of the animal field
  • The getAge method returns the value of the age field
  • implement a toString() method to display the pet name, type and age

2. Write a test class to test your Pet class. Make sure you have three different types of pets. (three Pet objects)


1
Expert's answer
2021-04-06T18:41:48-0400
public class Pet {
    private String name;
    private String animal;
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public String getAnimal() {
        return animal;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return name+" "+animal+" "+age;
    }
}

public class PetTest {
    public static void main(String[] args) {
        Pet cat = new Pet();
        cat.setName("Tom");
        cat.setAnimal("Cat");
        cat.setAge(3);

        Pet dog = new Pet();
        dog.setName("Goofy");
        dog.setAnimal("Dog");
        dog.setAge(7);

        Pet bird = new Pet();
        bird.setName("Tweety");
        bird.setAnimal("Bird");
        bird.setAge(2);

        System.out.println(cat);
        System.out.println(dog);
        System.out.println(bird);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog