What does "this()" method mean?
Solution 1:
This is constructor overloading:
public class Diagraph {
public Diagraph(int n) {
// Constructor code
}
public Digraph(In in) {
this(in.readInt()); // Calls the constructor above.
int E = in.readInt();
for (int i = 0; i < E; i++) {
int v = in.readInt();
int w = in.readInt();
addEdge(v, w);
}
}
}
You can tell this code is a constructor and not a method by the lack of a return type.
This is pretty similar to calling super()
in the first line of the constructor in order to initialize the extended class. You should call this()
(or any other overloading of this()
) in the first line of your constructor and thus avoid constructor code duplications.
You can also have a look at this post: Constructor overloading in Java - best practice
Solution 2:
Using this() as a function like that, essentially calls the Constructor of the class. This allows you to all the generic initializations in one constructor and have specializations in others. So in this piece of code for example, the call to this(in.readInt())
is calling the Digraph constructor that has one int argument.
Solution 3:
This code snippet is a constructor.
This call to this
calls another constructor of the same class
public App(int input) {
}
public App(String input) {
this(Integer.parseInt(input));
}
In the above example we have a constructor that takes an int
and one that takes a String
. The constructor that takes a String
converts the String
to an int
and then delegates to the int
constructor.
Note that a call to another constructor or a superclass constructor (super()
) must be the first line in a constructor.
Maybe take a look at this for a more detailed explanation of constructor overloading.
Solution 4:
It's nearly the same
public class Test {
public Test(int i) { /*construct*/ }
public Test(int i, String s){ this(i); /*construct*/ }
}