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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.