This information probably exists somewhere but I don't know what keywords to use to find it
So if the main method foo of my program creates an object bar of another class, how can bar reference the methods in foo.
public class Foo{
Bar baz = new Bar();
public Foo(){}
public int getNum(){
return 3;
}
}
public class Bar{
public Bar(){
/*Somehow use getNum*/
}
}
I could probably have Bar extend foo, or create a foo object.
The problem is a foo object already exists (the one that created bar) and I just don't know how to reference it.
Objects do not know what classes created them*, so you need to tell them by passing a reference to the constructor:
private final Foo foo;
public Bar(Foo foo) {
this.foo = foo;
}
...
public class Foo {
Bar baz = new Bar(this);
...
}
* Objects of inner classes get a reference to their outer object implicitly, but it may not necessarily be the class that created them. The only objects that always get a reference to the creating class are objects of method-local and anonymous classes.
Create Foo field in the Bar class, then create a constructor for Bar that takes Foo parameters. Use the constructor to set the instance of your field. Now all you have to do is pass the this keyword into the constructor:
public class Foo {
Bar baz = new Bar(this);
public Foo() {
}
public int getNum() {
return 3;
}
}
public class Bar {
private Foo parent;
public Bar(Foo foo) {
this.parent = foo;
}
public Foo getParent() {
return parent;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With