Java: Write a class Cow with attributes name (string) and numLegs (int). Do not make the attributes private. Make a constructor with two parameters to instantiate the attributes, and a toString method that prints only the name, a comma, a space, and the number of legs (e.g. Bossie, 3).
Add a main method that makes two cows, Bossie with 3 legs and Elsie with 4 legs, and puts them into an ArrayList. Print the ArrayList, one element per line, using an enhanced for loop.
import java.util.ArrayList; public class Cow { private String name; private int numLegs; public Cow(String name, int numLegs) { this.name = name; this.numLegs = numLegs; } @Override public String toString() { return name + ", " + numLegs; } public static void main(String[] args) { ArrayList<Cow> cows = new ArrayList<>(); cows.add(new Cow("Bossie", 3)); cows.add(new Cow("Elsie", 4)); for (Cow cow: cows) { System.out.println(cow); } } }
Get Answers For Free
Most questions answered within 1 hours.