简体   繁体   中英

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

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 ?

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

    }   
}

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.

I have two methods, a boolean and a static void, and I want to use a variable in the boolean method to create a switch condition in the static void method. Any help pls?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM