Java: Call a method from a "contained" class
public class A {
private B obj = new B(); // Inside this object
// do I need a reference to here?
// (In order to call method1())
public A(){ ... }
private voi开发者_高级运维d method1(){ ... }
private void method2(){ ... }
}
// Other package
public class B {
private JButton bt1 = new JButton("Button");
public B(){
...
bt1.addMouseListener(new MouseActionsListener(this));
}
public class MouseActionsListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent event)
{
/*
* I need to call method1() HERE!!!
*/
}
}
}
Is it possible to call a method of the class A from the class B in that position?
The problem is that I have a list of B objects in A, and whenever a button is clicked in one of the B objects a change has to be made in A.Thank you!
There is no implicit association that would allow you to go from B
to A
.
You will need to:
- change
B
to keep a reference to the corresponding instance ofA
; - initialize that reference in
B
's constructor; - use it call
A
's methods.
In code:
public class A {
private B obj;
public A() {
obj = new B(this);
...
}
public void method1(){ ... }
public void method2(){ ... }
}
public class B {
private final A _a;
public B(A a) {
_a = a;
}
public class MouseActionsListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent event) {
_a.method1();
}
}
No. You would need to have a reference back to an instance of A
from your B
class.
Yes, you have to have a reference back (As has already been said).
I'm only adding in here to mention that this can get a little sticky. If you can, I suggest redesigning your structure so that you don't need the double-reference, if not I highly recommend that you don't try to do the setting in constructors--instead call a.init(b) and/or b.init(a) to set the values.
It may work as written for now but as time goes on initializing in constructors will cause increasing limitations and frustrations. Not that you can't refactor later, but I guess I'm just suggesting this so you don't waste too much time banging your head before you decide to refactor.
If you think about it, doing it that way makes it so that you can't instantiate just one of them, making testing more difficult, and if you add any further dependencies to the construction of the class it can become impossible (this starts to reach the same kind of complexity as multiple inheritance).
You may also want to consider either having both add themselves to a common source as listeners or using an event bus (Probably the cleanest and simplest solution).
精彩评论