将父母加入其子女

时间:2014-07-25 14:04:01

标签: java oop

我有:

class A
{
     public String getID() { return "id of A";}
}

class B extends A
{ 
     public String getID() { return "id of B"; }
}

class C {
 public A returnA() { 
    return new A(); 
  } 
}

现在我需要做的事情:

C c = new C();
B b = (B)c.returnA(); 
String id = b.getId();

但我无法访问C.returnA()的实施,我无法将其返回类型更改为B.

3 个答案:

答案 0 :(得分: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();
    }
}

请注意,必须覆盖A的所有方法,以确保在装饰元素上调用方法。 (这里otherMethodOfA就是一个例子)

像这样使用:

C c = new C();
B b = new B(c.returnA());
String id = b.getID();

答案 1 :(得分:0)

那不行。 c.returnA()会返回AA B。 (B A,但这与此无关。)

答案 2 :(得分:0)

njzk2的答案是完美的。无论如何,如果您最终阅读了这篇文章并像我一样,不喜欢覆盖所有方法,则可以这样做:

public class B extends A {

    public B(A nonDecorated) {
        this.anotherValueOfA = nonDecorated.getAnotherValueOfA();
    }

    @Override
    public String getID() {
        return "id of B";
    }
}

不需要重写每个方法,并且使用其父对象的值构造对象。

当然,这是假设A类为:

class A {
    private int anotherValueOfA;
    public String getID() {return "id of A";}
    public int getAnotherValueOfA() {return this.anotherValueOfA;}
}
相关问题