Reputation: 459
Lets say I have 3 Classes: A
, Data
, and B
I pass a variable from class A which sets that passed variable to a public static
variable in class Data with Data's class method
setData()
and trying to get the same value (which i was assigned in class A
) in class
B
using Data's class method
getData()
.
methods in Data class are public
and static
public class Data{
public static string nameD;
public static void setData(String name){ nameD = name; }
public static String getData(){ return nameD; }
}
public class A{
String nameA="Test";
Data.setData(nameA); }
public class B{
String nameB; nameB = Data.getData(); println(nameB); }
But gives null string in class B
.
How can i do that.?
Upvotes: 0
Views: 8281
Reputation: 634
just call first class A to set the value for class Data then call class B to get the value inside the data.
ex:
public class A{
String nameA="Test";
public A() {
Data.setData(nameA);
}
}
public class B{
String nameB;
B() {
nameB = Data.getData();
System.out.println(nameB);
}
}
public class Data{
public static String nameD;
public static void setData(String name){ nameD = name; }
public static String getData(){ return nameD; }
}
then if u made the following, you will got ur value new A(); new B();
Upvotes: 1
Reputation: 106
It's not valid code, because you cannot execute a statement like Data.setData()
outside of any method.
If you put this code in a method inside class A and then call this method in your main program in the correct order (before calling getData()
), it will still be very confusing code, but you should get your desired result.
Upvotes: 0
Reputation: 647
You could pass the object and have a static field in the object you pass.
Upvotes: 0