B
继承A
而D
继承C
。 D
实例被传递给 B
实例来操作,但是没有覆盖变量或创建新的引用 D
类型看不到 bStuff()
.
class Ryrich_A {
public void aStuff() { System.out.println("a-type stuff"); }
}
class Ryrich_B extends Ryrich_A {
public void bStuff() { System.out.println("b-type stuff"); }
}
class Ryrich_C {
Ryrich_A a;
Ryrich_C(Ryrich_A a) {
this.a = a;
}
}
class Ryrich_D extends Ryrich_C{
Ryrich_D(Ryrich_B b) {
super(b);
}
public void doStuff() {
a.aStuff();
// a.bStuff(); --problem--
}
public static void main(String[] args) {
new Ryrich_D(new Ryrich_B()).doStuff();
}
}
最佳答案
如果 C
的子类应该与 A
的特定子类一起工作(即 D
总是与 B
一起工作>),你可以使 C
通用:
class C<T extends A> {
T a;
C(T a) {
this.a = a;
}
...
}
class D extends C<B> {
D(B b) {
super(b);
}
...
}
关于java - 重铸一个继承的领域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23156299/