Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

java - calling a function in a class's "owner" class

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...