java 我们如何在不借助父类的情况下将变量从一个方法传递到同一个类中的另一个方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37854137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:53:16  来源:igfitidea点击:

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

javavariablesmethods

提问by Arnav Das

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 ato method bwithout taking the help of parent class ?

但我想知道是否有在我的前程序中的任何方式来传递变量宣布method amethod b不考虑父类的帮助?

回答by Carlo

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[])
    {

    }   
}

回答by Abhishek

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()

并调用b(String t,int k)from 方法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.

但是请记住,当您在 Java 中将某些内容作为参数传递时,它是作为按值调用传递的。