问题
let's take a simple program like this :
public class Dope
{
public void a()
{
String t = "my";
int k = 6;
}
public void b()
{
System.out.println(t+" "+k);/*here it shows an error of not recognizing any variable*/
}
public static void main(String Ss[])
{
}
}
although i can correct it by just resorting to this way :
public class Dope
{
String t;
int k ;
public void a()
{
t = "my";
k = 6;
}
public void b()
{
System.out.println(t+" "+k);
}
public static void main(String Ss[])
{
}
}
but i wanted to know if there's any way in my former program to pass the variables declared in method a
to method b
without taking the help of parent class ?
回答1:
You can declare b method with two parameters, as following example:
public class Dope
{
public void a()
{
String t = "my";
int k = 6;
b(t, k);
}
public void b(String t, int k)
{
System.out.println(t+" "+k);
}
public static void main(String Ss[])
{
}
}
回答2:
Change the signature of your method from b()
to b(String t,int k)
public void b(String t, int k)
{
System.out.println(t+" "+k);
}
and give a call to b(String t,int k)
from method a()
By using these method parameters you need not change the scope of the variables.
But remember when ever you pass something as a parameter in Java it is passed as call by value.
来源:https://stackoverflow.com/questions/37854137/how-can-we-pass-variables-from-one-method-to-another-in-the-same-class-without-t