如何在不借助父类的帮助下将变量从一个方法传递到另一个方法?

时间:2021-07-25 23:12:37

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 ?

但我想知道我以前的程序中是否有任何方法将方法a中声明的变量传递给方法b而不需要父类的帮助?

2 个解决方案

#1


2  

You can declare b method with two parameters, as following example:

您可以使用两个参数声明b方法,如下例所示:

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


1  

Change the signature of your method from b() to b(String t,int k)

将方法的签名从b()更改为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()

从方法a()调用b(String t,int k)

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.

但是请记住,当你在Java中传递某些东西作为参数时,它会按值调用传递。

#1


2  

You can declare b method with two parameters, as following example:

您可以使用两个参数声明b方法,如下例所示:

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


1  

Change the signature of your method from b() to b(String t,int k)

将方法的签名从b()更改为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()

从方法a()调用b(String t,int k)

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.

但是请记住,当你在Java中传递某些东西作为参数时,它会按值调用传递。