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?
This would work:
There are 3 possibilities :
1) making dostuff() static and call it like
2) Creating an instance of Owner inside the class Bar
3) Inject an Owner instance through the constructor
Now, instance
b
ofBar
has a reference too
of typeOwner
and can doo.doStuff()
whenever needed.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.
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.