【问题标题】:Initialize final variable in two constructors在两个构造函数中初始化最终变量
【发布时间】:2018-10-31 14:47:09
【问题描述】:

我有两个变量。并且应该创建两个构造函数。

 private int size;
 final private Class clazz;

第一:

public SomeConstr(int size) {
    if (size <= 0) {
        this.size = 0;
        IllegalArgumentException argumentException = new IllegalArgumentException();
        logger.log(Level.SEVERE, "", argumentException);
        throw argumentException;
    }
    else
        this.size = size;

    this.clazz = Device.class;       
    }
}

第二:

public ComeConstrSecond(int size, Class clazz) {
   this(size);

   if (clazz == null || !Device.class.isAssignableFrom(clazz)) {
         logger.log(Level.SEVERE, "");
         throw new IllegalArgumentException();
   }

   this.clazz = clazz; 
 }

当我在第二个构造函数中初始化this.clazz = clazz 时,我遇到了have been assigned to 这样的问题。如果我必须使用this(size)clazz 的写入初始化有多正确?

【问题讨论】:

    标签: java constructor dry


    【解决方案1】:

    以另一种方式将您的构造函数链接起来 - 从具有部分信息的构造函数到具有所有信息的构造函数:

    public SomeConstr(int size) {
       this(size, Device.class);
    }
    
    public SomeConstr(int size, Class clazz) {
        if (size <= 0) {
            IllegalArgumentException argumentException = new IllegalArgumentException();
            logger.log(Level.SEVERE, "", argumentException);
            throw argumentException;
        }
        if (clazz == null || !Device.class.isAssignableFrom(clazz)) {
            logger.log(Level.SEVERE, "");
            throw new IllegalArgumentException();
        }
        this.size = size;
        this.clazz = clazz;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-23
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2015-02-19
      • 2014-08-26
      • 2012-04-22
      相关资源
      最近更新 更多