Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...