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
.
You can get to it by: main.inString
where main
is the name of the class where public static
variable is declared.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With