Calling a class function of the owner class

The following pseudo code brings my question pretty well ...

class Owner { Bar b = new Bar(); dostuff(){...} } class Bar { Bar() { //I want to call Owner.dostuff() here } } 

Bar b is β€œowned” (what is the right word?) On Owner (has β€œhas”). So, how would an object of type Bar call Owner.dostuff() ?

At first I thought super(); but this is for inherited classes. Then I thought that I need an interface, am I on the right track?

+4
source share
8 answers

If dostuff is the usual method, you need to pass the Bar instance.

 class Owner { Bar b = new Bar(this); dostuff(){...} } class Bar { Bar(Owner owner) { owner.dostuff(); } } 

Please note that there can be many owners in Bar, not some realistic way of knowing who they are.

Edit: You may be looking for the 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 } } } 
+6
source

This will work:

 class Owner { Bar b = new Bar(this); dostuff(){...} } class Bar { Bar(Owner myOwner) { myOwner.dostuff(); } } 
+3
source

I think you are looking for nested clans. Nested Sun classes

So you can write outer.this.doStuff();

Take a look at this topic: Method of an external class to call a class

+3
source

As you put it, there is no way to call the "owner" in Java.

Object A has a reference to object B, does not mean that object B even knows that object A exists.

The only way to achieve this is to either inherit (as you said yourself) or pass an instance of the Owner object to the Bar constructor.

+2
source
 class Owner { Bar b = null; Owner(){ b = new Bar(this); } dostuff(){...} } class Bar { Owner o = null; Bar(Owner o) { this.o = o; } } 

Now the b of Bar instance has a reference to o type Owner and can do o.doStuff() if necessary.

+2
source
 class Owner { Bar b = new Bar(this); dostuff(){...} } class Bar { Bar(Owner owner) { owner.doStuff(); } } 
+1
source

I think you wrote the code, this is impossible to do. But if you declare Bar as the owner's inner class , you can get a closer solution.

+1
source

There are 3 possibilities:

1) by making dostuff () static and calling it

 Owner.dostuff() 

2) Creating an Owner instance inside the Bar class

 class Bar { Owner o; public Owner() { o = new Owner(); o.dostuff(); } } 

3) Paste the owner instance through the constructor

 class Bar { public Owner(Owner o) { o.dostuff(); } } 
+1
source

Source: https://habr.com/ru/post/1396707/


All Articles