Create a Java class called Dog that contains two private instance variables: nam
ID: 3671887 • Letter: C
Question
Create a Java class called Dog that contains two private instance variables:
name: (type String)
age: (type int)
The class should include the following methods:
a constructor that initializes the two instance variables based in input parameters
getter and setter methods for the two instance variables
dogAgeInPersonYears: a method to compute and return the age of the dog in “person years” (seven times the dog’s age).
toString: a method that returns a one-line description of the dog.
Write an application named DogDriver that demonstrates Dog capabilities.
Explanation / Answer
package com.tcs;
public class Dog {
private String name;
private int age;
public Dog(String name, int age){
this.name=name;
this.age=age;
}
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 int dogAgeInPerson(){
int ageInPerson=0;
ageInPerson=7*age;
return ageInPerson;
}
@Override
public String toString() {
// TODO Auto-generated method stub
System.out.println("It one-line description of the dog");
return "Name of the dog is " + name + " and the age is " + age ;
}
}
package com.tcs;
public class DogDriver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog dog = new Dog("Blacky",12);
System.out.println("Age of the dog in person years is : "+dog.dogAgeInPerson());
System.out.println(dog.toString());
}
}