オブジェクトのリストを作成するために別のクラス NoisyPetStore を使用するクラス GoodPetStoreClient が与えられました。これは、インターフェイス MakesSound を実装する Cat、Dog、Cow のリストを作成し、NoisyPetStore を変更して確実にGoodPetStoreClient が適切にコンパイルされることを確認します。私は自分が欠けているものを解決しようとしてきましたが、これまで運が悪かったので、経験豊富な洞察をいただければ幸いです。
ありがとう!
コードは次のとおりです public class GoodPetStoreClient {
public static void main(String[] args) {
NoisyPetStore petStore = new NoisyPetStore();
petStore.addPet(new Cat());
petStore.addPet(new Cow());
System.out.println("I bought an animal, and it goes: " + petStore.buyNewestPet().makeNoise()); //moo...
System.out.println("The rest of the pet store goes: " + petStore.makeHugeNoise()); //meow
System.out.println("I bought another animal, and it goes: " + petStore.buyNewestPet().makeNoise()); //meow
petStore.addPet(new Dog());
System.out.println("The pet store now goes: " + petStore.buyNewestPet().makeNoise());
}
private static class CollisionInSpace {
// makes no sound at all
}
}
import java.util.ArrayList; java.util.List をインポートします。
public class NoisyPetStore
{
//Stores pets
private List list;
public NoisyPetStore()
{
list = new ArrayList();
}
/* add a pet to the pet store after checking
* whether or not the object implements
* <MakesSound>
* @param o takes in a object of an unspecified
* class
**/
public void addPet(Object o )
{
//check if the instance implements the MakesSound interface
if(o instanceof MakesSound)
{
list.add(o);
}
}
/* get the last pet from the store by accessing
* the last item in the list, and hence the one
* which has been added most recently
**/
public Object buyNewestPet()
{
Object ans = null;
if (list.size() > 0)
{
ans = list.remove(list.size() - 1);
}
return ((MakesSound)ans);
}
/* creates a string representation of all of the noises
* made by pets which have been added to the list using
* a <StringBuilder>
* @return returns a String representation of all the noises
* made by the pets in the list
**/
public String makeHugeNoise() {
StringBuilder ans = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
ans.append(((MakesSound) list.get(i)).makeNoise());
}
return ans.toString();
}
}
public class Cat implements MakesSound
{
String sound;
/* Constructor for Cat object
* takes in no parameters and instantiates
* the instance variable sound
**/
public Cat()
{
sound = "Meeow";
}
/* Overrides the <makeNoise> method defined by the
* <MakeSounds> interface
* takes in no parameters and returns the sound made
* by a cat, represented as a <String> {@link String}
**/
@Override
public String makeNoise()
{
String s = sound;
return s;
}
}
//dog and cow have identical codes to cat, with the exception that they produce the sounds "Woof!" and "Moo!" respectively.