简体   繁体   English

我可以使派生类从Java的基类继承派生成员吗?

[英]Can I make a derived class inherit a derived member from its base class in Java?

I have code that looks like this: 我的代码看起来像这样:

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();
    }
}

However, there is a problem with this code. 但是,此代码存在问题。 I'm storing a reference to the member in two places, but if one changes and the other does not, there could be trouble. 我在两个地方存储对该成员的引用,但如果一个更改而另一个没有,则可能会有问题。 I know that in Java, an inherited method can narrow down its return type (and perhaps arguments, but I'm not certain) to a derived class. 我知道在Java中,一个继承的方法可以将其返回类型(可能是参数,但我不确定)缩小到派生类。 Is the same true of fields? 田野是一样的吗?

You can accomplish this better with generics. 使用泛型可以更好地完成此任务。

public class AWrapper<T extends A>
{
    public T member;
    public AWrapper(T member)
    {
        this.member = member;
    }

    public void doStuffWithMember()
    {
        a.doStuff();
    }
}    

public class BWrapper extends Wrapper<B>
{
    public BWrapper(B member)
    {
        super(member);
    }

    public void doStuffWithMember()
    {
        member.doMoreStuff();
    }
}

The fact that the subclass wrapper specifies the type of B allows you to access B's functions in the BWrapper, without storing an additional reference. 子类包装器指定B类型的事实允许您在BWrapper中访问B的函数,而无需存储其他引用。

In your class BWrapper you have to remove the line public B member; 在您的BWrapper类中,您必须删除public B member; . And in the method doMoreStuffWithMember() replace the line with: 在方法中, doMoreStuffWithMember()将行替换为:

((B) member).doMoreStuff();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM