Java 中的接口继承
Interface inheritence in Java
在:
// services
public interface Mother { public Collection<? extends Father> getMamaStuff() {}}
public interface Daughter extends Mother {}
// data
public interface Father { public String getPapaStuff() }
public interface Son extends Father { public String playLoudMusic() }
为什么不允许这样做:
public class Clazz {
Clazz(Daughter daughter) {//boilerplate}
public Collection<Son> idk = doughter.getMamaStuff();
}
- 是不是因为没办法知道Father是哪个实现的
克拉兹会得到吗?
- 解决这个问题的好方法是什么?
- instanceof 在这种情况下是好的做法吗?
在我看来,没有办法绕过类型检查。
修复损坏的提供代码后。
编译器只知道我们从母亲那里得到的是它扩展父亲的东西。它不知道它具体是 son
。
编译器不会为 ju 转换。
所以我们在 collection 中可以拥有的是 something that extends father
// services
public interface Mother { public Collection<? extends Father> getMamaStuff(); {}}
public interface Daughter extends Mother {}
// data
public interface Father { public String getPapaStuff(); }
public interface Son extends Father { public String playLoudMusic(); }
public class Clazz {
Clazz(Daughter daughter) {//boilerplate}
Collection<? extends Father> idk = daughter.getMamaStuff();
}
}
不允许的原因:
interface Feline { }
interface Kitten extends Feline {}
interface Tiger extends Feline {}
...
Cage<? extends Feline> makeCage();
// at this point, it's actually really important that
// the right kind of cage was created...
makeCage().put(new Tiger());
参数化 Mother
可能适用于您的情况:
public interface Mother<T extends Father> {
public Collection<T> getMamaStuff(); {}
}
在:
// services
public interface Mother { public Collection<? extends Father> getMamaStuff() {}}
public interface Daughter extends Mother {}
// data
public interface Father { public String getPapaStuff() }
public interface Son extends Father { public String playLoudMusic() }
为什么不允许这样做:
public class Clazz {
Clazz(Daughter daughter) {//boilerplate}
public Collection<Son> idk = doughter.getMamaStuff();
}
- 是不是因为没办法知道Father是哪个实现的 克拉兹会得到吗?
- 解决这个问题的好方法是什么?
- instanceof 在这种情况下是好的做法吗?
在我看来,没有办法绕过类型检查。
修复损坏的提供代码后。
编译器只知道我们从母亲那里得到的是它扩展父亲的东西。它不知道它具体是 son
。
编译器不会为 ju 转换。
所以我们在 collection 中可以拥有的是 something that extends father
// services
public interface Mother { public Collection<? extends Father> getMamaStuff(); {}}
public interface Daughter extends Mother {}
// data
public interface Father { public String getPapaStuff(); }
public interface Son extends Father { public String playLoudMusic(); }
public class Clazz {
Clazz(Daughter daughter) {//boilerplate}
Collection<? extends Father> idk = daughter.getMamaStuff();
}
}
不允许的原因:
interface Feline { }
interface Kitten extends Feline {}
interface Tiger extends Feline {}
...
Cage<? extends Feline> makeCage();
// at this point, it's actually really important that
// the right kind of cage was created...
makeCage().put(new Tiger());
参数化 Mother
可能适用于您的情况:
public interface Mother<T extends Father> {
public Collection<T> getMamaStuff(); {}
}