Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java How can an object reference the class that created it

Tags:

java

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.

like image 748
Aristides L Avatar asked Jun 26 '26 02:06

Aristides L


2 Answers

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.

like image 182
Sergey Kalinichenko Avatar answered Jun 28 '26 17:06

Sergey Kalinichenko


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;
    }
}
like image 42
Cardinal System Avatar answered Jun 28 '26 17:06

Cardinal System



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!