2022-03-01

Two classes which have instances of each other ,give a stack over flow error [duplicate]

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 I know why it happens but I can't find a proper solution .on the other hand 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();
     }
   }
 }


No comments:

Post a Comment