如果我设置类的属性的值并使用final,是否必须将属性初始化为类构造函数的参数?例如,我已将长度为“60”的属性机架设置为

public class Runs {
    Teams team;
    final int racklength=60;
    int xposteam;

     public Runs (Teams y) {
         team=y;
     }
}

最佳答案

您必须始终初始化final属性,但是可以就地(首先声明它)或在其构造函数(或构造函数)中进行初始化:

public class Runs {
    Teams team;
    final int racklength; // initialization postponed
    int xposteam;

     // constructor defaulting racklength to 60
     public Runs (Teams y){
         team=y;
         racklength=60;
    }

     // constructor with variable initialization of final attribute
     public Runs (int l, Teams y){
         team=y;
         racklength=l;
    }

     // error since racklength is not initialized during construction
     public Runs (){
         team=null
    }
}

10-06 06:32