在另一个方法的构造函数中初始化最终变量 [英] Initialize final variable within constructor in another method

查看:59
本文介绍了在另一个方法的构造函数中初始化最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题并不大,但是仍然让我对如何使用Java构造函数和方法有所思考.

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.

我有一个常数,表示我声明为final的半径,并且也将其公开,以供所有人查看.当我永远不会更改半径时,我不希望我的代码被getRadius()方法所困扰.

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

我希望它最终像

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

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

我知道我可能会将该方法用于其他目的,这就是给我提供空白字段RADIUS可能未初始化"的原因,所以我想知道是否有一种方法可以添加出于清洁的考虑,将仅在构造函数中使用.

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

这篇关于在另一个方法的构造函数中初始化最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆