您将得到 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);
}
}
请检查链接@为什么静态变量被认为是邪恶的?