在两个构造函数中初始化最终变量

时间:2018-10-31 14:47:09

标签: java constructor dry

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

 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的问题。如果必须使用clazz,如何正确this(size)进行写初始化?

1 个答案:

答案 0 :(得分:14)

反过来束缚您的构造函数-从具有部分信息的构造器到具有所有信息的构造器:

column master_column format a20
column col2 format A10 heading &date_0
column col3 format A15 heading &date_1

select  
   'a' as master_column,
   'b' as col2,
   'c' as col3
from 
  dual;

MASTER_COLUMN        2018-10-31 2018-10-30     
-------------------- ---------- ---------------
a                    b          c