what does this() mean in Java [duplicate]

我的未来我决定 提交于 2019-12-03 12:34:16
Peter Lawrey

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!