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