6

I am a beginner learning 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?

1
  • 3
    Use/Learn Method arguments. Through arguments you can pass values to the method. Commented Feb 23, 2011 at 1:38

3 Answers 3

7

You need to pass in an instance of myClassA into a constructor for yourClass, and store a reference to it.

class yourClass {

    private myClassA classAInstance;

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

    void I_AM_a_button_press()  // function
    {
        classAInstance.printVariable();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

You need to make a new instance of myClassA and call that method from that new object

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

Or you can pass an instance of myClassA in through a constructor

Comments

1

Try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.