Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does this() mean in Java [duplicate]

Tags:

java

this

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.

like image 519
Jay Avatar asked Nov 11 '10 18:11

Jay


2 Answers

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.

like image 90
Peter Lawrey Avatar answered Oct 25 '22 04:10

Peter Lawrey


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
        }

}
like image 26
Dave Costa Avatar answered Oct 25 '22 02:10

Dave Costa