简体   繁体   中英

Initialize final variable within constructor in another method

I have a problem which isn't really that big, but still gives me some thought as to how Java constructors and methods are used.

I have a constant representing a radius I declare final, and also make it public for everyone to see. I don't want my code littered with getRadius() methods when I'm never ever going to change the radius.

I want to initialize the constant within the constructor as I want to apply certain criteria before assigning the radius, certain conditions have to be met. However, these conditions do take up some space, and I'd like to put them in some other method, to make the constructor cleaner.

The whole thing would initially look like this

public MyProblematicClass {
   public final int radius;
   public MyProblematicClass(... variables ...) {
      if(... long criteria ...) {
         radius = n;
      }
   }
}

and I'd love it to end up like

public MyProblematicClass {
       public final int radius;
       public MyProblematicClass(... variables ...) {
          this.setRadiuswithCriteria(criteria);
}

private void setRadiuswithCriteria(criteria crit) {
   if(... crit ...) {
      radius = n;
   }

I understand that I could potentially use the method for other purposes and that's the reason for giving me a 'blank field RADIUS may not have been initialized, so I'd like to know if there is a way to add a method which will only be used in constructors, for cleanliness's sake.

How about (using small caps for radius, because it is not a constant, as pointed out in the comments):

public MyProblematicClass(... variables ...) {
    radius = getRadiusWithCriteria(criteria);
}

private int getRadiusWithCriteria(criteria crit) {
   if(... crit ...) {
      return n;
   } else {
      return 0;
   }
}

You cannot assign to final variable outside constructor. As you said, method:

setRadiuswithCriteria(criteria crit) {
   if(... crit ...) {
      RADIUS = n;
   }

Can be used outside constructor.

And you must set final variable to some value in constructor, not just after checking some criteria (always, not sometimes).

However, you might move the code outside the constructor, using the returned value of some function. Example:

class MyClass {
    private final double i;
    public MyClass() {
        i = someCalculation();
    }
    private double someCalculation() {
        return Math.random();
    }
}

How about doing like this?

public MyProblematicClass {
    public final int RADIUS;
    public MyProblematicClass(... variables ...) {
       RADIUS = this.setRadiuswithCriteria(criteria);
}

private int setRadiuswithCriteria(criteria crit) {
if(... crit ...) {
    return n;
}
return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM