2013-04-07 89 views
33

我遇到了这个代码块,有这一行我不会理解它的意义或做什么。“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.variable的,但什么是this()

+0

@Avi我当时就在想这个听起来很熟悉。 – 2013-04-10 23:06:17

回答

48

这是构造函数重载:

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

您也可以看看这个帖子:Constructor overloading in Java - best practice

+0

谢谢你...很好的信息确实 – Gattsu 2014-01-29 09:08:11

10

使用这个()作为这样的一个功能,本质上调用类的构造函数。这允许您在一个构造函数中进行所有通用初始化,并在其他方面进行专业化。所以在这段代码中,例如对this(in.readInt())的调用正在调用具有一个int参数的Digraph构造函数。

3

类有向图的其他构造与int参数。

Digraph(int param) { /* */ } 
8

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

这次调用this调用同一类

public App(int input) { 
} 

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

的另一个构造在上面的例子,我们有一个构造函数的int,而另一种一String。这需要一个String构造函数转换Stringint,然后委托给int构造。

注意,另一个构造函数或超类构造函数(super())的调用必须在构造函数中的第一道防线。

也许看一看this的构造函数重载的更详细的解释。

3

调用this基本调用类的构造函数。 例如,如果你扩展的东西,比add(JComponent)一起,你可以这样做:this.add(JComponent).

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 
    } 

} 
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()构造函数,因为它会导致死锁状态。

希望这将帮助你:)

4

这是几乎相同的

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

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

} 
+0

你的意见是搞乱你的右括号 – 2013-04-10 23:07:20

+0

@亚历山大这是因为我从OP复制他们为清晰。 – Antimony 2013-04-10 23:24:46