1

我有树类。

class MyObject{
    public void DoSomething()
    {
        here I need to call method add from class base.
    }
}

class base
{
    protected final void add(){}      
}

class extended extends base {
    private MyObject pObject = new MyObject();
    ...
    {
        pObject.DoSomething();
    }
}

我可以为扩展类扩展的每个变体创建类,但是我需要使用的类型只有在扩展类已经启动后才可用。

如何base.add()MyObject内部方法调用?

4

2 回答 2

0

您可以通过以下几种方式做到这一点:

  • extended在课堂上参考你的MyObject班级。在类中实例化MyObject变量时extended,将extended.

像这样的东西:

class MyObject{
    private base baseObj;

    public MyObject(base baseObj){
        this.baseObj = baseObj;
    }

    public void DoSomething()
    {
        //here I need to call method add from class base.
            //use baseObj to call the methods
    }
}


class base
{
    protected final void add(){}      
}


class extended extends base {
    private MyObject pObject;
    ...

    public extended(){
        pObject = new MyObject(this);
    }

    {
        pObject.DoSomething();
    }
}
  • 声明base类中的方法static。这样你就可以调用方法而不需要base类的实例。

像这样的东西:

class MyObject{

    public void DoSomething()
    {
        //here I need to call method add from class base.
        //call like this
        base.add();
    }
}


class base
{
    protected static final void add(){}      
}


class extended extends base {
    private MyObject pObject;
    ...

    public extended(){
        pObject = new MyObject(this);
    }

    {
        pObject.DoSomething();
    }
}

还有一件事:这是题外话,但您可能想阅读Java Naming Conventions。类名以小写开头是您在命名约定中找不到的。

于 2012-09-19T04:44:24.597 回答
0

像这样的虚拟代码:

class MyObject{
    public void DoSomething(Base base)
    {
        base.add();
    }
}

class extended extends base {
    private MyObject pObject = new MyObject();
    ...
    {
        pObject.DoSomething(this);
    }
}
于 2012-09-19T04:49:52.040 回答