Passing variables between classes in Java!

I am starting to learn Java. I have two classes,

public class myClassA {
    //It contains the main function

    yourClass tc = new yourClass();

    .... many codes...

    public void printVariable()
    {
        // print here
    }

}


class yourClass {

    void I_AM_a_button_press()  // function
    {
        // I want to call printVariable() in myClassA here, But how?
    }
}

How can I call a method defined in one class from another?

+3
source share
3 answers

You need to pass the instance myClassAto the constructor for yourClassand keep a reference to it.

class yourClass {

    private myClassA classAInstance;

    public yourClass(myClassA a)
    {
        classAInstance = a;
    }

    void I_AM_a_button_press()  // function
    {
        classAInstance.printVariable();
    }
}
+4
source

You need to create a new instance of myClassA and call this method from this new object

void I_AM_a_button_press()  // function
    {
        myClassA a = new myClassA();
        a.printVariable();
    }

Or you can pass an instance of myClassA through the constructor

+3
source

Try:

public void I_AM_a_button_press(){
  myClassA a = new  myClassA();
  a.printVariable();
}
+1
source

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


All Articles