gpt4 book ai didi

java - 如何使变量的范围全局(而不使其实际上全局)

转载 作者:行者123 更新时间:2023-12-01 07:39:09 26 4
gpt4 key购买 nike

如何使字符串变量的范围(在Java中)全局。以便从另一个函数访问它例如

//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

}

任何帮助...谢谢

最佳答案

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

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

public class YourClass
{
private String yourStringVar;

public int pleaseGiveYourFunctionProperNames(String s){
this.yourStringVar = s;
}
public void thisFunctionPrintsValueOfMyStringVar(){
System.out.println(yourStringVar);
}
}

根据具体情况,您必须评估变量所需的范围,并且必须了解增加范围的含义(更多访问 = 潜在更多依赖项 = 更难跟踪)。

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

要创建一个具有全局作用域的变量(确切地说,在 Java 中不存在全局变量之类的东西),您需要创建一个带有静态变量的类。

public class GlobalVariablesExample
{
public static string GlobalVariable;
}

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

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

这可能非常强大,也非常危险,因为它可能会导致您意想不到的奇怪行为,并且您会失去面向对象编程赋予您的许多能力,因此请小心使用它。

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"
}
}

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

另外,请不要将变量命名为 a、b、c。并且不要将变量命名为 func1,func2。它不会让你的应用程序变慢,也不会因为输入一些额外的字母而让你丧命。

关于java - 如何使变量的范围全局(而不使其实际上全局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7591227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com