这个()在Java中是什么意思

时间:2010-11-11 18:43:54

标签: java this

this()在Java中意味着什么?

它看起来只有在放

时才有效
this();

在类变量区域。

有人对此有所了解吗?

感谢。

7 个答案:

答案 0 :(得分:7)

这意味着您正在从另一个构造函数调用默认构造函数。它必须是第一个声明,如果你有,你不能使用super()。看到它的使用是相当罕见的。

答案 1 :(得分:6)

这是对无参数构造函数的调用,您可以将其作为另一个构造函数中的第一个语句来调用,以避免重复代码。

public class Test {

        public Test() {
        }

        public Test(int i) {
          this();
          // Do something with i
        }

}

答案 2 :(得分:3)

它表示“没有参数的调用构造函数”。例如:

public class X {
    public X() {
        // Something.
    }
    public X(int a) {
        this();   // X() will be called.
        // Something other.
    }
}

答案 3 :(得分:1)

调用this()将调用没有参数的类的构造函数。

您可以这样使用它:

public MyObj() { this.name = "Me!"; }
public MyObj(int age) { this(); this.age = age; }

答案 4 :(得分:1)

它是对包含类的构造函数的调用。请参阅:http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html

答案 5 :(得分:0)

请参阅此处的示例:http://leepoint.net/notes-java/oop/constructors/constructor.html

您可以使用this()

显式调用构造函数

答案 6 :(得分:0)

一个类调用自己的默认构造函数。用参数来看它更常见。