简体   繁体   中英

Confusion with Constructor chaining

I am trying to understand few constructor chaining, I know that Calling a constructor from the another constructor of same class is known as Constructor chaining,

When we use this inside a constructer, we are actually calling another constructor that we already have defined, but the program that I am trying to understand is weird,

public AESCipher(Key key) {
        this(key.getEncoded());
    }

    /**
     * Create AESCipher based on existing {@link Key} and Initial Vector (iv) in bytes
     *
     * @param key Key
     */
    public AESCipher(Key key, byte[] iv) {
        this(key.getEncoded(), iv);
    }

    /**
     * <p>Create AESCipher using a byte[] array as a key</p>
     * <p/>
     * <p><strong>NOTE:</strong> Uses an Initial Vector of 16 0x0 bytes. This should not be used to create strong security.</p>
     *
     * @param key Key
     */
    public AESCipher(byte[] key) {
        this(key, INITIAL_IV);
    }

    private AESCipher(byte[] key, byte[] iv) {
        try {
            this.secretKeySpec = new SecretKeySpec(key, "AES");
            this.iv = new IvParameterSpec(iv);
            this.cipher = Cipher.getInstance(ALGORITHM_AES256);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw Throwables.propagate(e);
        }
    }

In the first constructor, this line is used this(key.getEncoded()) , which constructor is this line calling ? there is no constructor before it in fact there is no constructor with one parameter.

and in the 3rd constructor, there is just one argument of type byte[] , and this is what happening inside is,

this(key, INITIAL_IV);

it is chaining a constructor with two parameters, one of type key and of of type byte[] , so it is chaining this constructor AESCipher(Key key, byte[] iv) , this is fine, but still...what is happening in the first constructor , and why there is a need of 4 constructors at first place.

PS: I just didn't post this question, I have spent like 4hours trying to understand what is happening but its too confusing.

Here is the complete code,

https://github.com/mike-ensor/aes-256-encryption-utility/blob/master/src/main/java/com/acquitygroup/encryption/AESCipher.java

The first constructor is calling the third constructor: public AESCipher(byte[] key) .

As far as why there are 4 constructors in the first place, it's intended to encapsulate the logic that deals with turning a Key into a byte[] , and to allow for the user to use a different initial vector if they so choose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM