2011-09-29 65 views
0

我怎样才能让一个字符串变量(在Java)的范围global.So它从另一个函数 如如何使变量全球范围(未做它实际上全球)

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

    } 

任何访问帮助...谢谢

回答

5

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。它不会让你的应用程序变慢,并且它不会让你输入一些额外的字母。

+0

+1为缺点的解释和示例 – Gandalf

+0

非常感谢:-) – user841852

1

嗯。您显然需要面向对象编程方面的一些经验。在OO中没有“全局”变量。但是任何定义为类中成员(方法外)的变量在该类中都是全局变量。

public class MyClass { 

    private String myVar; // this can be accessed everywhere in MyClass 

    public void func1(String s) { 
     myVar = s; 
    } 

    public void func2(String q) { // why is q needed here? It's not used 
     System.out.println(myVar); 
    } 

} 

所以func2会输出s的值,只要你先调用func1。

final Myclass myClass = new MyClass(); 
myClass.func1("value"); 
myClass.func2("whatever"); // will output "value" 

此外,为什么在你的例子中返回int的方法?它们应该是无效的。

+0

'myVar'不能是最终的,如果它从func1()分配。 –

+0

@Guillaume你不明白我的观点...我的要点是func1改变S的值并将它保存在b中,然后func2打印改变了s的值根据b – user841852

+0

最后编辑出来,谢谢Bala R,我不应该在晚上写代码:) – Guillaume