如何从字段访问父方法?

时间:2012-09-19 04:28:52

标签: java

我有树类。

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

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

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

2 个答案:

答案 0 :(得分: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 class 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。让类名以小写开头是你在命名约定中找不到的东西。

答案 1 :(得分:0)

像这样的虚拟代码:

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

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