Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...