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

2020-02-14 02:40发布

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 is 'owned' (whats the proper word?) by Owner (it 'has a'). So how would an object of type Bar call Owner.dostuff()?

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?

标签: java
8条回答
女痞
2楼-- · 2020-02-14 03:31

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
      }
   }
}
查看更多
迷人小祖宗
3楼-- · 2020-02-14 03:33

I think you are looking for nested Clases Nested Classes Sun

This way u can write outer.this.doStuff();

Have a look to that topic: Inner class call outer class method

查看更多
登录 后发表回答