javaconstructorthis

What's the use of this() in a class?


Looking at Linkedlist.java, I've observed the overloaded constructors, one of which contains an empty this(). Generally I have seen this with default params. Whats the use of this() with no params in it?

 /**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

Solution

  • This is called constructor chaining. It is the mechanism that enables objects to be initialized starting from the constructor of their most general superclass (Object) and moving down to the more specific ones (each level initializing the new object to a valid state for its class before moving on to the next).

    A constructor can choose which other constructor of the current class (denoted by this) or the parent class (denoted by super) will be invoked before this one is run. The default chaining option is (implicitly) super(), unless something else is specified (or if a parameterless constructor in the parent class is not visible).

    In your case, this() means that the constructor LinkedList(Collection<? extends E> c) will first call the LinkedList() constructor. While in your snippet it is a no-op, its presence ensures that any changes in the initialization strategy of the parameterless constructor will be also adopted by the other one. So it makes changing the initialization logic of the class a little less error prone.