calling a function in a class's “owner” class

前端 未结 8 1181
醉酒成梦
醉酒成梦 2020-12-20 20:35

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

class Owner {
    Bar b = new Bar();

    dostuff(){...}
}    

class Bar {
    Bar() {
              


        
8条回答
  •  心在旅途
    2020-12-20 21:04

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

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

    Edit: 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
          }
       }
    }
    

提交回复
热议问题