English 中文(简体)
Can 我把一个衍生的阶层从 Java的基类继承一个衍生成员?
原标题:Can I make a derived class inherit a derived member from its base class in Java?

我有这样的守则:

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,一种继承的方法可以将其返回类型(或许是论点,但我并不肯定)缩小到一个衍生类别。 实地情况是否相同?

最佳回答

你们能够以通用语更好地做到这一点。

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

分层包装商具体指明了B类,允许你在BWrapper获得B项功能,而不必再加提及。

问题回答

在您的班次<代码>BWrapper中,你必须删除“条码”栏目:公名B成员;。 在<条码>上,“成员”(

((B) member).doMoreStuff();




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签