How to call a variable in another method?

前端 未结 4 1028
暖寄归人
暖寄归人 2021-01-17 00:04

How to call a variable in another method in the same class?

public void example(){    
    String x=\'name\';
}

public void take()         


        
相关标签:
4条回答
  • 2021-01-17 00:21

    First declare your method to accept a parameter:

    public void take(String s){
        // 
    }
    

    Then pass it:

    public void example(){
        String x = "name";
        take(x);
    }
    

    Using an instance variable is not a good choice, because it would require calling some code to set up the value before take() is called, and take() have no control over that, which could lead to bugs. Also it wouldn't be threadsafe.

    0 讨论(0)
  • 2021-01-17 00:25

    You make it an instance variable of the class:

    public class MyClass
    {
        String x;
    
        public void example(){ x = "name"; } // note the double quotes
        public void take(){ System.out.println( x ); }
    }
    
    0 讨论(0)
  • 2021-01-17 00:25

    Since they are in different scopes you can't.

    One way to get around this is to make x a member variable like so:

    String x;
    
    public void example(){
        this.x = "name";
    }
    
    public void take(){
        // Do stuff to this.x
    }
    
    0 讨论(0)
  • 2021-01-17 00:41
    public class Test
    {
    
    static String x;
    public static void method1
    {
    x="name";
    }
    
    public static void method2
    {
    
    System.out.println(+x);
    
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题