what does this() mean in Java [duplicate]

半城伤御伤魂 提交于 2019-12-04 20:33:32

问题


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

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