Write a class Cow that keeps track of the current weight of
Write a class Cow that keeps track of the current weight of a cow (as an \"int\" value, in pounds). The Cow class should have a constructor, set and get methods, and a toString method. Your Cow class should work with the following code:
 public class TestCows
 {
    public static void main(String [] args)
    {
       Cow spot = new Cow(650);
       Cow milkie = new Cow(770);
      
       milkie.setWeight(780);
      
       System.out.println(\"Milkie weighs: \" + milkie.getWeight());
      
       System.out.println(spot);   // generates toString output
       System.out.println(milkie);
    }
 }
to generate the following output:
 Milkie weighs: 780
 cow that weighs 650 pounds
 cow that weighs 780 pounds
Use good style and encapsulation (do not let the weight ever go to a negative value -- it should always be zero or larger). You do not have to include import statements or any comments.
Solution
Hi, Please find my implementation.
Please let me know in case of any issue.
########## Cow.java #############
public class Cow {
// instance variable
private int weight;
// constructor
public Cow(int w){
weight = w;
}
// getter and setter
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
// toString method
@Override
public String toString() {
return \"cow that weighs \"+weight+\" pounds\";
}
}
############# TestCows.java #########
public class TestCows
{
public static void main(String [] args)
{
Cow spot = new Cow(650);
Cow milkie = new Cow(770);
milkie.setWeight(780);
System.out.println(\"Milkie weighs: \" + milkie.getWeight());
System.out.println(spot); // generates toString output
System.out.println(milkie);
}
}
/*
Sample output:
Milkie weighs: 780
cow that weighs 650 pounds
cow that weighs 780 pounds
*/


