[Solved] Java How to make “Static” variable name to be dynamic


You provided very little information about what kind of logic this would be, but in any case it should be inside the class Child. Depending on what kind of logic it is I would probably put it inside the constructor.


Suppose you have the following:

    public class Child(){
       public static int age = 1;

       public Child(){
       }
    }

    public class School(){
       int var_age;

       public School(){
          var_age = Child.age;
       }
    }

With this code the variable var_age in the class School will always be assigned to the same value. That would be 1 in this case. If you want to make it depend on your logic you will have to implement it somewher (in class Child, since you’re not allowed to edit class School). There are two obvious ways to do this;

  • First way of doing it – The Constructor-way:

    public class Child(){
       public static int age = 1;
    
       public Child(){ 
          age = yourLogic(); // Assign age depending on your logic here!
       }
    }
    

With this way of doing it, your variable age will have a default value, 1, and as soon as an object of type Child is being created, it will take on the value defined by your logic. Judging from your feedback however, what you probably need is the second version.

  • The second way of doing it – The field-way:

    public class Child(){
       public static int age = yourLogic(); // Assign age to logic here!
    
       public Child(){
       }
    }
    

This way, the variable age will have the value defined by your logic as a default value, so even if no instance of class Child is being created. This is probably what you were looking for. However note:
Depending on how computationally complicated your logic is, this can be a very bad practice.


By the way, DO NOT confuse the java static with the antonym of “dynamic”. static in a java sense merely means that the variable is bound to the type instead of the instance / Object. That means it can be accessed without having to call or create an instance of the surrounding class. If you want the opposite of dynamic, that would be final in java.

6

solved Java How to make “Static” variable name to be dynamic