This () and this

Does Java have this() ?

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

+4
source share
4 answers

this is a link to the current instance. this() is the default constructor call. super() is an explicit call to the default constructor of the superclass.

+12
source

this is a link to the current object. this() - call the default constructor; it is legal only inside another constructor and only as the first statement in the constructor. You can also call super() to call the default constructor for the superclass (again, only as the first constructor statement). In fact, this is automatically added by the compiler if the code does not have this() or super() (with or without arguments). 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 } } 
+7
source

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

+1
source

this is a java keyword used to store the reference identifier of the current object.
So far, this() is the default constructor call in the java program .

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 created an object of your class using a parameterized constructor, but this() must be the first in your 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(); } 
+1
source

Source: https://habr.com/ru/post/1394133/


All Articles