Get variable in other classes

后端 未结 4 2004
旧时难觅i
旧时难觅i 2020-11-30 15:14

I need to get variable inString in other class. How can I do this?

public class main {
    public static StringBuffer inString;


    public sta         


        
4条回答
  •  春和景丽
    2020-11-30 15:51

    You will get null because inString is never initialized as rightly pointed by Robert Kilar in the comment.

    You refer to static variables by using the class name.

    Example ClassName.variablename. In your case

        main.inString 
    

    Run your main class. When you run inString is initialized in the constructor of the class. Now you can refer to the same in Myclass as below.

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

    Now in MyClass refer to the static variable.

    class MyClass {
    
    public MyClass() {
        System.out.println("............."+main.inString);// refer to static variable
    }
    }
    

    You can also pass variables to the constructor of a class.

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

    Then in Myclass

     public class MyClass
     {
            public MyClass(StringBuffer value)
            {
              System.out.println("............."+value);
            }
     } 
    

    Please check the link @ Why are static variables considered evil?

提交回复
热议问题