444,173 views
25 votes
25 votes
Write a program that implements a class called Dog that contains instance data that represent the dog's name and age. • define the Dog constructor to accept and initialize instance data. • create a method to compute and return the age of the dog in "person-years" (note: dog age in person-years is seven times a dog's age). • Include a toString method that returns a one-line description of the dog • Write a driver class called Kennel, whose main method instantiated and updates several Dog objects

User Jagz S
by
2.6k points

1 Answer

18 votes
18 votes

Answer:

Dog.java:

Dog{

//Declare instance variables

private String name;

private int age;

//Create the constructor with two parameters, and initialize the instance variables

public Dog(String name, int age){

this.name = name;

this.age = age;

}

//get methods

public String getName(){

return name;

}

public int getAge(){

return age;

}

//set methods

public void setName(String name){

this.name = name;

}

public void setAge(int age){

this.age = age;

}

//calculateAgeInPersonYears() method to calculate the age in person years by multiplying the age by 7

public int calculateAgeInPersonYears(){

return 7 * getAge();

}

//toString method to return the description of the dog

public String toString(){

return "Name: " + getName() + ", Age: " + getAge() + ", Age in Person Years: " + calculateAgeInPersonYears();

}

}

Kennel.java:

public class Kennel

{

public static void main(String[] args) {

//Create two dog objects using the constructor

Dog dog1 = new Dog("Dog1", 2);

Dog dog2 = new Dog("Dog2", 5);

//Print their information using the toString method

System.out.println(dog1.toString());

System.out.println(dog2.toString());

//Update the first dog's name using setName method

dog1.setName("Doggy");

System.out.println(dog1.toString());

//Update the second dog's age using setAge method

dog2.setAge(1);

System.out.println(dog2.toString());

}

}

Step-by-step explanation:

*The code is in Java.

You may see the explanations as comments in the code

User Henk Jansen
by
2.9k points