如何在另一个方法中调用变量? [英] How to call a variable in another method?

查看:62
本文介绍了如何在另一个方法中调用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在同一个 class 中的另一个方法中调用变量?

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

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

public void take(){
    /*how to call x variable*/
}

推荐答案

首先声明您的方法以接受参数:

First declare your method to accept a parameter:

public void take(String s){
    // 
}

然后通过它:

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


使用实例变量不是一个好的选择,因为在调用 take()之前,需要调用一些代码来设置值,然后take()无法对此进行控制,这可能会导致错误.而且它也不是线程安全的.


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.

这篇关于如何在另一个方法中调用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆