在另一个方法中调用变量(JAVA) [英] calling variable in another method (JAVA)

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

问题描述

我想问一下,如何在同一个类中调用另一个方法中的变量

i want to ask ,how to calling 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.

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

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