Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables between classes, in Java!

Tags:

java

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?

like image 531
Droid-Bird Avatar asked Feb 23 '11 01:02

Droid-Bird


People also ask

How do you pass a variable from one class to another in Java?

So we will create getter and setter method of these variables. In Class2 ,create object of Class1 as Class1 class1 = new Class1(); Now you can use its methods and variable through by calling Class1 getter methods. If there is public variable in Class1 then you can access them directly by Class1 object as class1.name.

How do you pass a variable from one class to another?

You can create the object of one class and using this object you call other class variables and methods, but make sure the accessiblity will be as public. We can use interface class A and by implementing A into B, can use the variable of class A into B.

How do you pass variables in Java?

Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

Can we pass arguments to class in Java?

Arguments in Java are always passed-by-value. During method invocation, a copy of each argument, whether its a value or reference, is created in stack memory which is then passed to the method.


1 Answers

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();
    }
}
like image 186
ide Avatar answered Oct 28 '22 03:10

ide