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?
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.
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.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With