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:12

This would work:

class Owner {

    Bar b = new Bar(this);

    dostuff(){...}
}    

class Bar {
    Bar(Owner myOwner) {
        myOwner.dostuff();
    }
}
查看更多
做个烂人
3楼-- · 2020-02-14 03:15

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();
   }
}
查看更多
家丑人穷心不美
4楼-- · 2020-02-14 03:17
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.

查看更多
ゆ 、 Hurt°
5楼-- · 2020-02-14 03:17

I think the way you have written the code, it is not possible to do. But if you declare Bar as inner class of Owner, you might get a closer solution.

查看更多
迷人小祖宗
6楼-- · 2020-02-14 03:19
class Owner {

    Bar b = new Bar(this);

    dostuff(){...}
}    

class Bar {
    Bar(Owner owner) {
       owner.doStuff();
    }
}
查看更多
Explosion°爆炸
7楼-- · 2020-02-14 03:28

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.

查看更多
登录 后发表回答