我有这样的守则:
public class A
{
public void doStuff()
{
System.out.print("Stuff successfully done");
}
}
public class B extends A
{
public void doStuff()
{
System.out.print("Stuff successfully done, but in a different way");
}
public void doMoreStuff()
{
System.out.print("More advanced stuff successully done");
}
}
public class AWrapper
{
public A member;
public AWrapper(A member)
{
this.member = member;
}
public void doStuffWithMember()
{
a.doStuff();
}
}
public class BWrapper extends AWrapper
{
public B member;
public BWrapper(B member)
{
super(member); //Pointer to member stored in two places:
this.member = member; //Not great if one changes, but the other does not
}
public void doStuffWithMember()
{
member.doMoreStuff();
}
}
然而,该法存在问题。 我在两个地方储存提及该成员的字句,但如果一个变化和另一个变化不定,可能会出现麻烦。 我知道,在 Java,一种继承的方法可以将其返回类型(或许是论点,但我并不肯定)缩小到一个衍生类别。 实地情况是否相同?