Initialize final variable in two constructors

Mentha :

I have two variables. And should make two constructors.

 private int size;
 final private Class clazz;

First:

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

Second:

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

When I initialise this.clazz = clazz in the second constructor, I have a problem like have been assigned to. How correct write initialisation for clazz if I must use this(size)?

Jon Skeet :

Chain your constructors the other way round - from the one with partial information to the one with all the information:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110718&siteId=1