Answered step by step
Verified Expert Solution
Question
1 Approved Answer
public interface Animal { String getSound(); String getName(); } public class Cow implements Animal { @Override public String getSound() { return moo; } @Override public
public interface Animal { String getSound(); String getName(); }
public class Cow implements Animal { @Override public String getSound() { return "moo"; } @Override public String getName() { return "cow"; } }
import java.util.Random; public class Chicken implements Animal{ @Override public String getSound() { Random random = new Random(); if(random.nextInt(2) == 0) { return "bawk!"; } else { return "cluck!"; } } @Override public String getName() { return "chicken"; } }
import java.util.ArrayList; import java.util.List; public class Farm { private Listanimals; public Farm() { animals = new ArrayList<>(); } public void addAnimal(Animal animal) { animals.add(animal); } public void sing() { for(int i = 0; i < animals.size(); ++i) { System.out.println("Old MacDonald had a farm. E-I-E-I-O!"); System.out.printf("And on that farm he had a %s. E-IE-I-O! With a %s %s here and a %s there ", animals.get(i).getName(), animals.get(i).getSound(), animals.get(i).getSound(), animals.get(i).getSound()); } } }
public class AnimalMain { public static void main(String[] args) { Farm farm = new Farm(); farm.addAnimal(new Cow()); farm.addAnimal(new Chicken()); farm.sing(); } }
Based on the class relationships above, circle the declarations that are legal.
a. Animal a = new Animal();
b. Animal b = new Cow();
c. Animal c = new Chicken();
d. Cow d = new Animal();
e. Cow e = new Chicken();
f. Chicken f = new Animal();
g. Chicken g = new Cow();
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started