Answer to Question #197749 in Java | JSP | JSF for Prince Emmanuel

Question #197749

Write a class named Pet,which should have the following data attributes:

a.__name(for the name of a pet)

__animal_type(for the type of animal that a pet is.Example values are ‘Dog’,

‘Cat’,and ‘Bird’)

__age(for the pet’s age)

The Pet class should have an__init__method that creates these attributes.

It should also have the following methods:

b.set_name:This method assigns a value to the__name field.

set_animal_type:This method assigns a value to the__animal_type field.

set_age:This method assigns a value to the__age field.

get_name:This method returns the value ofthe__name field.

get_animal_type:This method returns the value of the__animal_type field.

get_age:This method returns the value of the__age field.


1
Expert's answer
2021-05-24T16:53:26-0400
public class Pet {
	enum AnimalType {
		Cat, Dog, Bird
	}


	private AnimalType animalType;
	private String name;
	private int age;


Pet(String type, String n, int a)
{init(type, n, a);}


	public void init(String type, String n, int a) {
		animalType = AnimalType.valueOf(type);
		name = n;
		age = a;
	}


	public AnimalType getAnimalType() {
		return animalType;
	}


	public void setAnimalType(AnimalType animalType) {
		this.animalType = animalType;
	}


	public String getName() {
		return name;
	}


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


	public int getAge() {
		return age;
	}


	public void setAge(int age) {
		this.age = age;
	}
	
	public static void main(String args[]) {
		Pet cat = new Pet("Cat",  "Behemoth", 5), 
				dog = new Pet("Dog",  "Whitefang", 3), 
				eagle = new Pet("Bird",  "Buckbeak", 10);
		Pet pets[] = {cat, dog, eagle};
		for(Pet pet:pets)
			System.out.println(pet.getAnimalType()+" "+pet.getName()+", "+pet.getAge()+" years old.");		
	}
}

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
APPROVED BY CLIENTS