インターフェース:
package sandBox.ps.generics.compositePattern;
import java.util.Collection;
interface AnimalInterface {
String getID();
/*
* getAnimals can be:
* 1. AnimalInterface
* 2. Anything that implements/extends AnimalInterface (i.e. AnimalInterface or DogInterface)
*/
Collection<? extends AnimalInterface> getAnimals();
}
interface DogInterface extends AnimalInterface {
String getBreed();
}
クラス:
package sandBox.ps.generics.compositePattern;
import java.util.Collection;
import java.util.Collections;
class AnimalClass implements AnimalInterface {
private final String id;
private final Collection<? extends AnimalInterface> animals;
AnimalClass(final String id,
final Collection<? extends AnimalInterface> animals) {
this.id = id;
this.animals = animals;
}
@Override
public String getID() {
return this.id;
}
@Override
public Collection<? extends AnimalInterface> getAnimals() {
return this.animals;
}
}
class DogClass extends AnimalClass implements DogInterface {
private final String breed;
DogClass(final String id, final String breed) {
super(id, Collections.<AnimalInterface> emptyList());
this.breed = breed;
}
@Override
public String getBreed() {
return this.breed;
}
}
クラスのテスト:
package sandBox.ps.generics.compositePattern;
import java.util.ArrayList;
import java.util.Collection;
public class TestClass {
public void testA() {
// Dog Collection (Child)
final DogInterface dog = new DogClass("1", "Poodle");
final Collection<DogInterface> dogCol = new ArrayList<DogInterface>();
dogCol.add(dog);
// Animal Collection of Dogs (Parent)
final AnimalInterface animal = new AnimalClass("11", dogCol);
final Collection<AnimalInterface> parent = new ArrayList<AnimalInterface>();
parent.add(animal);
// Animal Collection of Animals (Grand-Parent)
final AnimalInterface grandParent = new AnimalClass("11", parent);
// Get Dog
for (final AnimalInterface parents : grandParent.getAnimals()) {
/* I know the this code would work.
* My question is, is there anyway to do this without explicit casting
for (final AnimalInterface child : parents.getAnimals()) {
if (child instanceof DogInterface) {
System.out.println(((DogInterface)child).getBreed());
}
}
*/
/* HERE: This is the part I am trying to solve.
* Do I use extends or super for AnimalInterface
* Is there any option such that I don't need to do a casting of some type
*/
for (final DogInterface child : parents.getAnimals()) {
System.out.println(child.getBreed());
}
}
}
}
質問:
- テストクラスの最後の行は、動物にアクセスしようとします。
- 私が理解しようとしているのは、明示的なキャストを避けるためにとにかくあるのかということです。
- これを機能させるextends、super、またはその他の一般的な用語の組み合わせはありますか?
- キャスティングが唯一のオプションである場合、それはどこで行われるべきですか?
- 私はすでにこれがうまくいくことを知っています:
for (final AnimalInterface child : parents.getAnimals()) { if (child instanceof DogInterface) { System.out.println(((DogInterface)child).getBreed()); } }