What does "this()" method mean?

Sugihara picture Sugihara · Apr 7, 2013 · Viewed 40.5k times · Source

I ran into this block of code, and there is this one line I don't quit understand the meaning or what it is doing.

public Digraph(In in) {
    this(in.readInt()); 
    int E = in.readInt();
    for (int i = 0; i < E; i++) {
        int v = in.readInt();
        int w = in.readInt();
        addEdge(v, w); 
    }
}

I understand what this.method() or this.variable are, but what is this()?

Answer

Avi picture Avi · Apr 7, 2013

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