我有两个父类和两个子类。我有迭代器方法的返回类型的问题,它始终是父类类型,子类不能覆盖它。
请考虑以下代码:
public class Attribute {}
public class Attributes implements Iterable<Attribute> {
protected ArrayList<Attribute> attrs = new ArrayList<Attribute>();
public Iterator<Attribute> iterator() {
return this.attrs.iterator();
}
}
// -------
public class Attr extends Attribute {}
public class Attrs extends Attributes {}
// -------
for (Attr attr : attrs) {
// Error! attrs.iterator() returns Attribute not Attr
}
for (Attribute attribute : attrs) {
Attr attr = (Attr) attribute;
// Works
}
是否可以覆盖迭代器返回类型?
答案 0 :(得分:1)
因此可接受以下覆盖:
public class Baa{
.....
public Baa returnSomething{
return this;
}
}
public class Foo extends Baa{
.....
@Override
public Foo returnSomething{
return this;
}
}
即使您正在查看对象仍然可以正常工作
public static void main(String[] args){
Baa test=new Foo(); //a Foo is a Baa so no problem
Baa getSomething=test.returnSomething(); //returns a Foo, but a foo can be used as as a baa so no problem
}
如果对于集合发生同样的事情似乎很方便,但是你可以轻而易举地创建一个会有运行时错误的例子
Collection<Intger> numbers=new ArrayList<Intger>();
Collection<Number> falseNumbers=(Collection<Number>)numbers; //pretend not an error
falseNumbers.add(new Double()); ////eeeek!
使用泛型,如Returning a Collection from a method that specifies that it returns Collection中所述,我们可以指出集合的最小和最大边界(基本上说它们只能包含可以转换为某种类型的对象。通过使用它我们可以创建一个不需要转换的迭代器:
public class Attribute {
protected ArrayList<Attribute> attributes = new ArrayList<Attribute>();
public Attribute(){
//holding an array of yourself seems strange, but I am replicating the code in the question
attributes.add(this);
}
public Iterator<? extends Attribute> iterator() {
return this.attributes.iterator();
}
public static void main(String[] args){
Attribute attribute=new Attribute();
Iterator<? extends Attribute> it1=attribute.iterator();
Attribute attributeInternat=it1.next();
Attr attr=new Attr();
Iterator<? extends Attr> it2=attr.iterator();
Attr attrInternat=it2.next();
}
}
public class Attr extends Attribute{
protected ArrayList<Attr> attrs2 = new ArrayList<Attr>();
public Attr(){
//holding an array of yourself seems strange, but I am replicating the code in the question
attrs2.add(this);
}
@Override
public Iterator<? extends Attr> iterator() {
return this.attrs2.iterator();
}
}
这确保没有铸造,一切都是完全类型安全的。