在类的“所有者"中调用函数班级 [英] calling a function in a class's "owner" class

查看:32
本文介绍了在类的“所有者"中调用函数班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的伪代码总结了我的问题,我想...

Following pseudocode sums up my question pretty well I think...

class Owner {
    Bar b = new Bar();

    dostuff(){...}
}    

class Bar {
    Bar() {
        //I want to call Owner.dostuff() here
    }
}

Bar b Owner (具有a")拥有"(正确的单词是什么?).那么 Bar 类型的对象如何调用 Owner.dostuff()?

Bar b is 'owned' (whats the proper word?) by Owner (it 'has a'). So how would an object of type Bar call Owner.dostuff()?

起初我在想 super(); ,但这是针对继承的类的.然后我在想通过一个接口,我走对了吗?

At first I was thinking super();, but that's for inherited classes. Then I was thinking pass an interface, am I on the right track?

推荐答案

如果dostuff是常规方法,则需要向Bar传递一个实例.

If dostuff is a regular method you need to pass Bar an instance.

class Owner {

   Bar b = new Bar(this);

   dostuff(){...}
}    

class Bar {
   Bar(Owner owner) {
      owner.dostuff();
   }
}

请注意,Bar可能有很多所有者,但没有任何现实的方式来确定他们是谁.

Note that there may be many owners to Bar and not any realistic way to find out who they are.

您可能正在寻找内部课程:样本和评论.

You might be looking for an Inner class: Sample and comments.

class Owner {

   InnerBar b = new InnerBar();

   void dostuff(){...}

   void doStuffToInnerBar(){
       b.doInnerBarStuf();
   }

   // InnerBar is like a member in Owner.
   class InnerBar { // not containing a method dostuff.
      InnerBar() { 
      // The creating owner object is very much like a 
      // an owner, or a wrapper around this object.
      }
      void doInnerBarStuff(){
         dostuff(); // method in Owner
      }
   }
}

这篇关于在类的“所有者"中调用函数班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆