Issue
There are two classes : Calculator and MenubarListener .
The Calculator class has an instance of MenubarListener , and now in MenubarListener class I need to access two methods of the Calculator class and invoke them .but when I make an instance of Calculator inside MenubarListener the compiler shows stack over flow error. obviously it falls in a loop .also I don't want to make these methods static,otherwise that will create other problems.
How can I access these two methods through the second class ?
Calculator class:
public class Calculator{
MenuBarListener menubarListener = new menubarListener(a,b,c);
.
.
.
public void method1{
//do something
}
public void method2{
//do something
}
}
MenubarListener class :
public class MenubarListener {
//when I make an instance of calculator class compiler shows stackoverflow error.
Calculator calculator = new Calculator;
int a, b,c;
MenubarListener (int a ,int b,int c ){
this.a = a ;
... }
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == helpItem) {
//I want to access these methods from Calculator class but it generates
calculator.method1();
}
}
}
Solution
You should NOT be creating a new instance of Calculator
inside MenubarListener
, just pass the reference to the Calculator
via constructor/setter:
public class Calculator{
MenuBarListener menubarListener = new MenuBarListener(this, 10, 20, 30);
//...
}
public class MenuBarListener {
final Calculator calculator;
int a, b, c;
MenuBarListener (Calculator calc, int a, int b, int c) {
this.calculator = calc;
this.a = a;
this.b = b;
this.c = c;
}
// ...
}
Answered By - Alex Rudenko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.