"this()"方法是什么意思?



我遇到了这段代码,有一行我不明白它的意思或它在做什么。

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.method()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()的任何重载),从而避免构造函数代码重复。

你也可以看看这篇文章:构造函数重载在Java -最佳实践

使用this()作为这样的函数,本质上是调用类的构造函数。这允许您在一个构造函数中进行所有泛型初始化,并在其他构造函数中进行专门化。因此,在这段代码中,例如,对this(in.readInt())的调用调用了具有一个int参数的Digraph构造函数。

这段代码是一个构造函数。

this的调用调用了同一类的另一个构造函数

public App(int input) {
}
public App(String input) {
    this(Integer.parseInt(input));
}

在上面的例子中,我们有一个接受intString的构造函数。接受String的构造函数将String转换为int,然后委托给int构造函数。

注意,对另一个构造函数或超类构造函数(super())的调用必须是构造函数的第一行。

几乎是一样的

public class Test {
    public Test(int i) { /*construct*/ }
    public Test(int i, String s){ this(i);  /*construct*/ }
}

调用this本质上是调用类Constructor。例如,如果您要扩展add(JComponent),那么您可以这样做:this.add(JComponent).

带int形参的diggraph类的另一个构造函数。

Digraph(int param) { /*  */ }

构造函数重载:

,

public class Test{
    Test(){
        this(10);  // calling constructor with one parameter 
        System.out.println("This is Default Constructor");
    }
    Test(int number1){
        this(10,20);   // calling constructor with two parameter
        System.out.println("This is Parametrized Constructor with one argument "+number1);
    }
    Test(int number1,int number2){
        System.out.println("This is Parametrized  Constructor  with two argument"+number1+" , "+number2);
    }

    public static void main(String args[]){
        Test t = new Test();
        // first default constructor,then constructor with 1 parameter , then constructor with 2 parameters will be called 
    }
}

this();是用来调用类中的另一个构造函数的构造函数,例如:-

class A{
  public A(int,int)
   { this(1.3,2.7);-->this will call default constructor
    //code
   }
 public A()
   {
     //code
   }
 public A(float,float)
   { this();-->this will call default type constructor
    //code
   }
}

注意:我没有在默认构造函数中使用this()构造函数,因为它会导致死锁状态。

希望对你有帮助

最新更新