This question already has an answer here:
- Whats the use of this() in linkedlist.java 2 answers
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.
This question already has an answer here:
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.
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.
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
}
}
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.
}
}
It is a call to a constructor of the containing class. See: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
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; }
See the example here: http://leepoint.net/notes-java/oop/constructors/constructor.html
You can call the constructor explicitly with this()
a class calling its own default constructor. It's more common to see it with arguments.