Assume that you have a working Cow class from the previous e
Assume that you have a working Cow class from the previous essay question. Write a Farm class where each Farm object keeps track of the name of the farm and a Cow that resides at the farm (use aggregation to keep track of the Cow). Your Farm class should work with the code shown below to generate the output shown below. You do not need to include import statements or comments. Create a Farm class that works with the code shown here:
public class FarmLand
{
public static void main(String [] args)
{
Cow spot = new Cow(650);
Cow milkie = new Cow(770);
Cow calf = new Cow(99);
Farm farm1 = new Farm(\"Johnson\", spot);
Farm farm2 = new Farm(\"Smith\", milkie);
farm2.setName(\"Smithson\");
System.out.println(\"farm2 is now: \" + farm2.getName());
Cow c = farm1.getCow();
System.out.println(\"farm1 has this cow: \" + c);
farm2.setCow(calf);
System.out.println(farm1);
System.out.println(farm2);
}
}
to generate the following output:
farm2 is now: Smithson
farm1 has this cow: cow that weighs 650 pounds
Johnson farm has a cow that weighs 650 pounds
Smithson farm has a cow that weighs 99 pounds
Your Farm class should have a constructor that works as shown above, plus set and get methods for both the name of the farm and the Cow object, and a toString method.
Solution
FarmLand.java
public class FarmLand
{
public static void main(String [] args)
{
Cow spot = new Cow(650);
Cow milkie = new Cow(770);
Cow calf = new Cow(99);
Farm farm1 = new Farm(\"Johnson\", spot);
Farm farm2 = new Farm(\"Smith\", milkie);
farm2.setName(\"Smithson\");
System.out.println(\"farm2 is now: \" + farm2.getName());
Cow c = farm1.getCow();
System.out.println(\"farm1 has this cow: \" + c);
farm2.setCow(calf);
System.out.println(farm1);
System.out.println(farm2);
}
}
Cow.java
public class Cow {
private int weight;
public Cow(int weight){
this.weight = weight;
}
public String toString(){
return \"cow that weighs \"+weight+\" pounds\";
}
}
Farm.java
public class Farm {
private String name;
private Cow cow;
public Farm(String name, Cow c){
this.cow = c;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Cow getCow() {
return cow;
}
public void setCow(Cow c) {
this.cow = c;
}
public String toString(){
return name+\" farm has a \"+cow;
}
}
Output:
farm2 is now: Smithson
farm1 has this cow: cow that weighs 650 pounds
Johnson farm has a cow that weighs 650 pounds
Smithson farm has a cow that weighs 99 pounds

