您將得到null,因爲inString永遠不會被初始化,正如Robert Kilar在評論中正確指出的那樣。
通過使用類名引用靜態變量。
示例ClassName.variablename。在你的情況下
main.inString
運行你的主類。當你運行inString在類的構造函數中被初始化。現在你可以在Myclass中引用同樣的內容。
public class main {
public static StringBuffer inString;
public main()
{
inString = new StringBuffer("Our aim is to make a 15 realistic game, where grinding powerlines and doing a tailwhip isn't easy, like in the real world. A game in which you will feel like you're actual riding. A game in which creativity and beauty are combined. ");
inString = new StringBuffer(inString.toString().replaceAll(" +", " "));
new MyClass();
}
public static void main(String[] args) {
new main();
}
}
現在在MyClass中引用靜態變量。
class MyClass {
public MyClass() {
System.out.println("............."+main.inString);// refer to static variable
}
}
您也可以將變量傳遞給類的構造函數。
public class main {
public StringBuffer inString;
public main()
{
inString = new StringBuffer("Our aim is to make a 15 realistic game, where grinding powerlines and doing a tailwhip isn't easy, like in the real world. A game in which you will feel like you're actual riding. A game in which creativity and beauty are combined. ");
inString = new StringBuffer(inString.toString().replaceAll(" +", " "));
new MyClass(inString);
}
public static void main(String[] args) {
new main();
}
}
然後在MYCLASS
public class MyClass
{
public MyClass(StringBuffer value)
{
System.out.println("............."+value);
}
}
請檢查鏈接@Why are static variables considered evil?
因爲你從來沒有初始化它在其他靜態無效主要你在那裏運行 – Yoda