我有:
class A
{
public String getID() { return "id of A";}
}
class B extends A
{
public String getID() { return "id of B"; }
}
Run Code Online (Sandbox Code Playgroud)
和
class C {
public A returnA() {
return new A();
}
}
Run Code Online (Sandbox Code Playgroud)
现在我需要做的事情:
C c = new C();
B b = (B)c.returnA();
String id = b.getId();
Run Code Online (Sandbox Code Playgroud)
但是我没有访问权限C.returnA(),而且我无法将其返回类型更改为B.
njz*_*zk2 15
您正在将父母投射到孩子身上.你永远不能那样做,因为new A()绝对不是B.
考虑一下:String extends Object.现在尝试施放(String) new Object().根本没有任何意义.
因为你的对象不是B反正的,所以没有办法让它有B的行为.
你想要的是使用装饰模式.见http://en.wikipedia.org/wiki/Decorator_pattern
下面是一个Decorator实现的示例:
public class B extends A {
private A decorated;
public B(A decorated) {
this.decorated = decorated;
}
@Override
public String getID() {
return "id of B";
}
@Override
public void otherMethodOfA() {
return decorated.otherMethodOfA();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,必须覆盖A的所有方法,以确保在装饰元素上调用方法.(这otherMethodOfA是一个例子)
使用这样:
C c = new C();
B b = new B(c.returnA());
String id = b.getID();
Run Code Online (Sandbox Code Playgroud)