如何使变量范围全局(不使其实际为全局)

use*_*852 0 java string global function

如何使String变量的范围(在Java中)全局.从另一个函数Eg访问它

//String b="null"; I don't want to do this... because if i do this, fun2 will print Null

    public int func1(String s)
    {

    String b=s;

    }

    public int func2(String q)
    {

    System.out.println(b);//b should be accessed here and should print value of s

    }
Run Code Online (Sandbox Code Playgroud)

任何帮助......谢谢

Dar*_*Teo 6

OOP中的一个基本概念是范围的概念:在几乎所有情况下,将变量的范围(即从中可见的范围)减小到其最小可行范围是明智的.

我假设你绝对需要在两个函数中使用该变量.因此,在这种情况下,最小可行范围将涵盖两种功能.

public class YourClass
{
   private String yourStringVar;

   public int pleaseGiveYourFunctionProperNames(String s){
      this.yourStringVar = s;
   }
   public void thisFunctionPrintsValueOfMyStringVar(){
      System.out.println(yourStringVar);
   }
}
Run Code Online (Sandbox Code Playgroud)

根据具体情况,您必须评估变量所需的范围,并且必须了解增加范围的含义(更多访问权限=可能更多的依赖关系=更难跟踪).

举个例子,假设您绝对需要它作为GLOBAL变量(正如您在问题中所说的那样).应用程序中的任何内容都可以访问具有全局范围的变量.这是非常危险的,我将证明.

要创建具有全局范围的变量(在Java中没有诸如全局变量之类的东西),您可以使用静态变量创建一个类.

public class GlobalVariablesExample
{
   public static string GlobalVariable;
}
Run Code Online (Sandbox Code Playgroud)

如果我要改变原始代码,它现在看起来像这样.

public class YourClass
{
   public int pleaseGiveYourFunctionProperNames(String s){
      GlobalVariablesExample.GlobalVariable = s;
   }
   public void thisFunctionPrintsValueOfMyStringVar(){
      System.out.println(GlobalVariablesExample.GlobalVariable);
   }
}
Run Code Online (Sandbox Code Playgroud)

这可能非常强大,而且非常危险,因为它可能导致你不期望的奇怪行为,并且你失去了面向对象编程给你的许多能力,所以要小心使用它.

public class YourApplication{
    public static void main(String args[]){
        YourClass instance1 = new YourClass();
        YourClass instance2 = new YourClass();

        instance1.pleaseGiveYourFunctionProperNames("Hello");
        instance1.thisFunctionPrintsValueOfMyStringVar(); // This prints "Hello"

        instance2.pleaseGiveYourFunctionProperNames("World");
        instance2.thisFunctionPrintsValueOfMyStringVar(); // This prints "World"
        instance1.thisFunctionPrintsValueOfMyStringVar(); // This prints "World, NOT Hello, as you'd expect"
    }
}
Run Code Online (Sandbox Code Playgroud)

始终评估变量的最小可行范围.不要让它比它需要的更容易访问.

另外,请不要将变量命名为a,b,c.并且不要将变量命名为func1,func2.它不会使你的应用程序变得更慢,并且它不会杀死你输入一些额外的字母.