2011-09-29 64 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