Following pseudocode sums up my question pretty well I think...
class Owner {
Bar b = new Bar();
dostuff(){...}
}
class Bar {
Bar() {
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();
}
}
This would work:
class Owner {
Bar b = new Bar(this);
dostuff(){...}
}
class Bar {
Bar(Owner myOwner) {
myOwner.dostuff();
}
}
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
}
}
}
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.
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.
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