How can we pass variables from one method to another in the same class without taking the help of parent class?

和自甴很熟 提交于 2019-12-25 19:04:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!