9

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.

Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
Jay
  • 245
  • 1
  • 5
  • 11
  • I answered a similar question on a different post. Might be helpful http://stackoverflow.com/questions/15867722/java-this-method-confusion – Avi Apr 09 '13 at 23:13

7 Answers7

7

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.

Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
6

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
        }

}
Dave Costa
  • 47,262
  • 8
  • 56
  • 72
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.
    }
}
Lavir the Whiolet
  • 1,006
  • 9
  • 18
1

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; }
Josh K
  • 28,364
  • 20
  • 86
  • 132
1

It is a call to a constructor of the containing class. See: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Kelly S. French
  • 12,198
  • 10
  • 63
  • 93
0

See the example here: http://leepoint.net/notes-java/oop/constructors/constructor.html

You can call the constructor explicitly with this()

Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
0

a class calling its own default constructor. It's more common to see it with arguments.

jon_darkstar
  • 16,398
  • 7
  • 29
  • 37