什么是“this()”方法是什么意思? [英] What does "this()" method mean?

查看:197
本文介绍了什么是“this()”方法是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到这个代码块,有一行我不退出理解的含义或它在做什么。

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); 
    }
}

方法()或 this.variable ,但是 this()

推荐答案

这是构造函数重载:

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); 
      }
   }
}

一个构造函数而不是一个缺少返回类型的方法。
这非常类似于在构造函数的第一行中调用 super(),以初始化扩展类。您应该在构造函数的第一行调用 this()(或任何其他重载 this()从而避免构造代码重复。

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.

您还可以看看这个帖子: Java中的构造方法重载 - 最佳做法

You can also have a look at this post: Constructor overloading in Java - best practice

这篇关于什么是“this()”方法是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆