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

I have a 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 keep the link to the participant in two places, but if someone changes and the other does not, there may be problems. I know that in Java, a legacy method can narrow its return type (and possibly arguments, but I'm not sure) to a derived class. Is the same true for fields?

+3
source share
2 answers

You can do it 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 shell specifies type B allows you to access the functions of B in BWrapper without having to maintain the sitelink.

+4

BWrapper public B member;. doMoreStuffWithMember() :

((B) member).doMoreStuff();
0

Source: https://habr.com/ru/post/1744988/


All Articles