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

前端 未结 8 1098
醉酒成梦
醉酒成梦 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();
       }
    }
    
    0 讨论(0)
  • 2020-12-20 21:02

    This would work:

    class Owner {
    
        Bar b = new Bar(this);
    
        dostuff(){...}
    }    
    
    class Bar {
        Bar(Owner myOwner) {
            myOwner.dostuff();
        }
    }
    
    0 讨论(0)
  • 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
          }
       }
    }
    
    0 讨论(0)
  • 2020-12-20 21:08

    In the way you're putting it, there is no way of calling the "owner" in Java.

    Object A has a reference of object B doesn't mean that object B even knows that object A exists.

    The only way to achieve this would be either though inheritance (like you said yourself), or by passing an instance of object Owner to the constructor of Bar.

    0 讨论(0)
  • 2020-12-20 21:09
    class Owner {
        Bar b = null;
        Owner(){
           b = new Bar(this);
        }
        dostuff(){...}
    }    
    
    class Bar {
        Owner o = null;
        Bar(Owner o) {
            this.o = o;
        }
    }
    

    Now, instance b of Bar has a reference to o of type Owner and can do o.doStuff() whenever needed.

    0 讨论(0)
  • 2020-12-20 21:17

    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

    0 讨论(0)
提交回复
热议问题