How to call a variable in another method?

前端 未结 4 1151
暖寄归人
暖寄归人 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.

提交回复
热议问题