this() and this

試著忘記壹切 提交于 2021-02-05 05:41:35

问题


Does Java has this()?

If so, what's the difference between this and this()?


回答1:


this is reference to current instance. this() is call to default constructor. super() is explicit call to default constructor of super class.




回答2:


this is a reference to the current object. this() is a call to the default constructor; it is only legal inside another constructor, and only as the first statement in the constructor. You can also call super() to invoke the default constructor for the superclass (again, only as the first statement of a constructor). This is, in fact, automatically inserted by the compiler if there is no this() or super() (with or without arguments) present in the code. For instance:

public class A {
    A() {
       super(); // call to default superclass constructor.
    }

    A(int arg) {
        this(); // invokes default constructor
        // do something special with arg
    }

    A(int arg, int arg2) {
        this(arg); // invokes above constructor
        // do something with arg2
    }
}



回答3:


Yes, Java has this(). this() calls the parameterless overload of the constructor for the current class. this is a reference to the current instance (object) of the class.




回答4:


this is a keyword in java used to hold the reference ID of current object.
While, this() is the call to the default constructor in your java program.

A code snippet for this():

class ThisTest{
    ThisTest(){
        System.out.println("this is the default constructor of your class");
    }
    ThisTest(int val){
        this();
        System.out.println("this is the parameterized constructor of your class and the passed value is "+val);
    }
    public static void main(String...args){
        ThisTest tt=new ThisTest(10);
    }
}

In the above code you'd created an object of your class by using the parameterized constructor but this() must be the first in your any constructor to call any other constructor.
You can also change the above code to:

ThisTest(){
    this(10);
    //above code
}
ThisTest(int val){
    //above code
}
public static void main(string...args){
    ThisTest tt=new ThisTest();
}


来源:https://stackoverflow.com/questions/9092046/this-and-this

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