47

このコード ブロックに出くわしましたが、その意味や何をしているのか理解できない行が 1 つあります。

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()ですか?

4

8 に答える 8

11

this() をそのような関数として使用すると、本質的にクラスのコンストラクターが呼び出されます。これにより、1 つのコンストラクターですべての一般的な初期化を行い、他のコンストラクターで特殊化することができます。たとえば、このコードでは、への呼び出しthis(in.readInt())は、1 つの int 引数を持つ Digraph コンストラクターを呼び出しています。

于 2013-04-07T20:59:11.750 に答える
4

ほぼ同じです

public class Test {
    public Test(int i) { /*construct*/ }

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

}
于 2013-04-10T23:06:10.217 に答える
2

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()デッドロック状態につながるため、デフォルトのコンストラクターでコンストラクターを 使用しませんでした。

これがあなたを助けることを願っています:)

于 2013-04-08T10:25:30.997 に答える
2

コンストラクターのオーバーロード:

元:

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 
    }

}
于 2013-04-08T05:13:21.973 に答える