接口:
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());
}
}
}
}
问题:
- 测试类的最后几行尝试访问动物。
- 我想弄清楚的是,无论如何要避免显式转换?
- 是否有任何扩展,超级或其他通用术语的组合可以使这项工作?
- 如果铸造是唯一的选择,应该在哪里完成?
- 我已经知道这会起作用:
for (final AnimalInterface child : parents.getAnimals()) { if (child instanceof DogInterface) { System.out.println(((DogInterface)child).getBreed()); } }