In: Computer Science
1. Lets construct a Dog class
2.Declare name, breed and weight as their private variables
3.Add a default constructor
4.Write a constructor with name, breed and weight as arguments
5.Add a toString method to the class
6.Add a equals method
7.Add a copy contructor
8.Add a bark method in Dog class
•This method checks if the weight is greater than 25 , then print (dog.name says woof!) else (dog.name say yip!)
// 1. Lets construct a Dog class
public class Dog {
// 2.Declare name, breed and weight as their private variables
private String name;
private String breed;
private int weight;
// 3.Add a default constructor
public Dog() {
}
// 4.Write a constructor with name, breed and weight as arguments
public Dog(String name, String breed, int weight) {
this.name = name;
this.breed = breed;
this.weight = weight;
}
// 5.Add a toString method to the class
@Override
public String toString() {
return "name='" + name + '\'' + ", breed='" + breed + '\'' + ", weight=" + weight;
}
// 6.Add a equals method
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dog dog = (Dog) o;
return weight == dog.weight && name.equals(dog.name) && breed.equals(dog.breed);
}
// 7.Add a copy contructor
public Dog(Dog dog) {
this.name = dog.name;
this.breed = dog.breed;
this.weight = dog.weight;
}
// 8.Add a bark method in Dog class
public void bark() {
// This method checks if the weight is greater than 25 , then print (dog.name says woof!) else (dog.name say yip!)
if (weight > 25) {
System.out.println(name + " says woof!");
} else {
System.out.println(name + " says yip!");
}
}
// Testing the class here. remove this method if not required.
public static void main(String[] args) {
Dog dog = new Dog("D", "B", 30);
dog.bark();
}
}
