I have a class with static variables as:
class Commons {
public static String DOMAIN ="www.mydomain.com";
public static String PRIVATE_AREA = DOMAIN + "/area.php";
}
And if I try to change DOMAIN from an Android Activity (or another java class) at runtime, the DOMAIN variable change but PRIVATE_AREA don't change. Why?
This is because the assignment of static fields happens once the class is loaded (occurs only one time) into the JVM. The PRIVATE_AREA
variable will not be updated when the DOMAIN
variable is changed.
public class Test {
public static String name = "Andrew";
public static String fullName = name + " Barnes";
public static void main(String[] args){
name = "Barry";
System.out.println(name); // Barry
System.out.println(fullName); // Andrew Barnes
}
}
I suggest that you use the following structure.
public class Test {
private static String name = "Andrew";
public static String fullName = name + " Barnes";
public static void setName(String nameArg) {
name = nameArg;
fullName = nameArg + " Barnes";
}
}
Test2.java
public class Test2 {
public static void main(String[] args){
System.out.println(Test.fullName); // Andrew Barnes
Test.setName("Barry");
System.out.println(Test.fullName); // Barry Barnes
}
}
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