Search code examples
javastringvariablesvariable-assignmentassign

Java: How to create "variable" fields with static parts?


I have a lot of fields that depend on the value of one field, like so:

private String root;
private String rootHide = root+"&hide";
private String rootApple = root+".apple.me";
...

Problem is, root is only assigned a value inside methods (non static, if that matters):

public myMethod () {
    root = "myRoot";
    System.out.println(rootHide);
    System.out.println(rootApple);
}

At the point of assigning a value to root, rootHide and rootApple are already assigned (null + their literal part).

I want, when root is assigned, the variables to "reassign" (or the variables to pick up the new root reference) and therefore result in "myRoot&hide" and "myRoot.apple.me" respectively


Solution

  • Two ways:

    Use a method to set root

    ...and also set the other two fields in that method:

    private void setRoot(String root) {
        this.root = root;
        rootHide = root+"&hide";
        rootApple = root+".apple.me";
    }
    

    You would always do setRoot("myRoot"); rather than root = "myRoot";

    Use a method to get the other two fields

    ...and compute their values in the method:

    private String getRootHide() {
        return root + "&hide";
    }
    
    private String getRootApple() {
        return root + ".apple.me";
    }
    

    You would then delete the fields rootHide and rootApple, and always call getRootHide() and getRootApple rather than accessing rootHide and rootApple.