Why does the this(6) command inside a constructor initialize the class array?

Asked

Viewed 177 times

5

In the code:

public class Lista{

        int [] a;
        int n;

        public Lista(){

                this(6);
        }

        public Lista(int i){

                this.a = new int [i];
                this.n = 0;
        }

        public static void main(String [] args){

                Lista l = new Lista();
                System.out.println("tamanho: " + l.a.length);

        }

}

As the first builder Lista() identifies that the command this(6); is initiating the array int a[] with the size?

3 answers

8


The this() is only calling the constructor, in this case it is an alias of it. It is the way to call this special method called constructor. Since it is possible to have a normal method exist in the class with the same name, at the moment it is building it cannot call by name because it may be the constructor or it may be a normal method, so the name is used this(). So in a way we can say that he’s actually calling Lista(6) which is the other constructor. And it is in this other constructor that is initiating the array normally.

Then a constructor that has a signature, in the case without parameters, is calling the other constructor that accepts a parameter with the size. If you call the constructor without parameters that is said formally by the language of standard builder it assumes a value for you, in case it is 6.

Obviously this second constructor is not just initiating the array, the other field too, but there’s no reason to let it be configured by the programmer outside the class, so you can see.

For an execution is not a problem, but often this method main() within this class is not suitable, it should be in class itself, it stands as a noise.

Your code has a abstraction leak (exposes the array out) and is not considered appropriate, even if it works, research more on the subject.

5

Because the expression this(6) will invoke the constructor method that takes an integer as parameter, because it is the type of parameter you are passing. Luckily this method is set just below:

public Lista(int i){
    this.a = new int [i];
    this.n = 0;
}

And he’s responsible for initializing the list a with the value of i, which is the parameter received, in this case 6.

2

Because Lista l = new Lista() refers to the call of the manufacturer Lista().

Inside this builder, there’s the builder Lista(int i) that is being called as follows

this(6)

When the second constructor is called, the array initialization occurs

this.a = new int [i]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.