OOP的基本概念之一就是范围的概念:在几乎所有情况下,将变量的范围(即可见范围)减小到其最小可行范围是明智的。
我打算假设你绝对需要在这两个函数中使用该变量。因此,这种情况下的最小可行范围将涵盖这两种功能。
public class YourClass
{
private String yourStringVar;
public int pleaseGiveYourFunctionProperNames(String s){
this.yourStringVar = s;
}
public void thisFunctionPrintsValueOfMyStringVar(){
System.out.println(yourStringVar);
}
}
根据不同的情况,你必须评估一个变量所需的范围,你必须了解增加范围的影响(更获得=可能更依赖=难以跟踪)。作为一个例子,假设你绝对需要它成为一个GLOBAL变量(如你在你的问题中所称的那样)。 Global范围的变量可以被应用程序中的任何东西访问。这是非常危险的,我将证明这一点。
要创建一个具有全局作用域的变量(在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。它不会让你的应用程序变慢,并且它不会让你输入一些额外的字母。
+1为缺点的解释和示例 – Gandalf
非常感谢:-) – user841852