Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
172 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...