问题
what does this()
mean in Java?
It looks it is only valid when put
this();
in the class variable area.
Any one has idea about this?
Thanks.
回答1:
It means you are calling the default constructor from another constructor. It has to be the first statement and you cannot use super() if you have. It is fairly rare to see it used.
回答2:
It's a call to the no-argument constructor, which you can call as the first statement in another constructor to avoid duplicating code.
public class Test {
public Test() {
}
public Test(int i) {
this();
// Do something with i
}
}
回答3:
It means "call constructor which is without arguments". Example:
public class X {
public X() {
// Something.
}
public X(int a) {
this(); // X() will be called.
// Something other.
}
}
回答4:
It is a call to a constructor of the containing class. See: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
回答5:
Calling this()
wil call the constructor of the class with no arguments.
You would use it like this:
public MyObj() { this.name = "Me!"; }
public MyObj(int age) { this(); this.age = age; }
回答6:
See the example here: http://leepoint.net/notes-java/oop/constructors/constructor.html
You can call the constructor explicitly with this()
回答7:
a class calling its own default constructor. It's more common to see it with arguments.
来源:https://stackoverflow.com/questions/4158028/what-does-this-mean-in-java