Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable in other classes

Tags:

java

class

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

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

So I try to use System.out.println(main.inString); in my Textcl.class, but get null.

like image 776
Anton A. Avatar asked Apr 14 '13 14:04

Anton A.


2 Answers

You can get to it by: main.inString where main is the name of the class where public static variable is declared.

like image 90
Yoda Avatar answered Sep 30 '22 10:09

Yoda


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?

like image 33
Raghunandan Avatar answered Sep 30 '22 12:09

Raghunandan