Following pseudocode sums up my question pretty well I think...
class Owner {
Bar b = new Bar();
dostuff(){...}
}
class Bar {
Bar() {
//I want to call Owner.dostuff() here
}
}
Bar b
is 'owned' (whats the proper word?) by Owner
(it 'has a'). So how would an object of type Bar
call Owner.dostuff()
?
At first I was thinking super();
, but that's for inherited classes. Then I was thinking pass an interface, am I on the right track?
Conclusion. In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.
We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.
When you declare a method in a Java class, you can allow or disallow other classes and object to call that method. You do this through the use of access specifiers. The Java language supports five distinct access levels for methods: private, private protected, protected, public, and, if left unspecified, "friendly".
To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;). If the method has parameters in the declaration, those parameters are passed within the parentheses () but this time without their datatypes specified.
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
}
}
}
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
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