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.
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.");
}
}
Comments
Leave a comment