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

前端 未结 8 1159
醉酒成梦
醉酒成梦 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 20:58

    There are 3 possibilities :

    1) making dostuff() static and call it like

    Owner.dostuff()
    

    2) Creating an instance of Owner inside the class Bar

    class Bar {
       Owner o;
       public Owner() {
         o = new Owner();
         o.dostuff();
       }
    }
    

    3) Inject an Owner instance through the constructor

    class Bar {
       public Owner(Owner o) {
         o.dostuff();
       }
    }
    

提交回复
热议问题