In: Computer Science
Write a java program using the information given
Design a class named Pet, which should have the following fields (i.e. instance variables):
name - The name field holds the name of a pet (a String type)
type - The type field holds the type of animal that a pet is (a String type). Example values are
“Dog”, “Cat”, and “Bird”.
age - The age field holds the pet’s age (an int type)
Include accessor methods (i.e. get methods) and mutator methods (i.e. set methods) for all the fields.
Once you have designed the class, design a program that creates an object of the class and prompts the user to enter the name, type, and age of his or her pet. This data should be stored in the object. Use the object’s accessor methods to retrieve the pet’s name, type, and age and display this data on the screen.
Sample Output:
Enter the name of your pet: Jimmy
Enter the type of your pet: Dog
Enter the age of your pet: 5
Here is the information you provided:
Pet Name: Jimmy
Pet Type: Dog
Pet Age: 5
Explanation:I have written the code for the Pet class and PetProgram class to show the output, please find the image attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//code
//Pet.java
public class Pet {
private String name;
private String type;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//PetProgram.java
import java.util.Scanner;
public class PetProgram {
public static void main(String[] args) {
Pet pet = new Pet();
Scanner input = new
Scanner(System.in);
System.out.print("Enter the name of
your pet: ");
String name = input.next();
System.out.print("Enter the type of
your pet: ");
String type = input.next();
System.out.print("Enter the age of
your pet: ");
int age = input.nextInt();
pet.setName(name);
pet.setType(type);
pet.setAge(age);
System.out.println("Here is the
information you provided:");
System.out.println("Pet Name: " +
pet.getName() + "\n" + "Pet Type: "
+ pet.getType() + "\n" + "Pet Age: " +
pet.getAge());
input.close();
}
}
Output: