DraxDomax
DraxDomax

Reputation: 1058

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

Upvotes: 0

Views: 66

Answers (2)

Simon Lowther
Simon Lowther

Reputation: 21

perhaps create a method that updates all variables when called

static update(String root){
rootHide = root+"&hide";
rootHide = root+"&hide";
}

call the method everytime you update root, or include setting of root so that it only needs to be called without first setting root.

Upvotes: -1

Sweeper
Sweeper

Reputation: 271645

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.

Upvotes: 4

Related Questions