在其他类中获取变量

ant*_*584 5 java class

我需要inString在其他课程中获得变量.我怎样才能做到这一点?

public class main {
    public static StringBuffer inString;


    public static void main(String[] args) {
        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(" +", " "));
        }
}
Run Code Online (Sandbox Code Playgroud)

所以我尝试System.out.println(main.inString);在我的Textcl.class中使用,但得到null.

Rag*_*dan 3

您将得到 null,因为 inString 从未像 Robert Kilar 在评论中正确指出的那样初始化。

您可以使用类名来引用静态变量。

示例:类名.变量名。在你的情况下

    main.inString 
Run Code Online (Sandbox Code Playgroud)

运行你的主类。当您运行时,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();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在 MyClass 中引用静态变量。

class MyClass {

public MyClass() {
    System.out.println("............."+main.inString);// refer to static variable
}
}
Run Code Online (Sandbox Code Playgroud)

您还可以将变量传递给类的构造函数。

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();

    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的班级

 public class MyClass
 {
        public MyClass(StringBuffer value)
        {
          System.out.println("............."+value);
        }
 } 
Run Code Online (Sandbox Code Playgroud)

请检查链接@为什么静态变量被认为是邪恶的?