Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Lets look at the three type of constructor calls one by one.Each one has special purpose associated with them. But the concept is simple and very interesting to explore. </p> <p>Case 1 :- This is default constructor with no arguments</p> <pre><code> public class MyClass{ public MyClass(){ } } </code></pre> <p>The compiler will automatically supply a no-argument constructor for you if you do not write one.Thus if you write <code>public class MyClass{ }</code> . </p> <p>This is equivalent to writing</p> <p><code>public class MyClass{<br> MyClass(){ } }</code></p> <p>Points to be noted :-</p> <ol> <li><p>Compiler automatically provide "super" when you do not use super "as the first line of the constructor". NOTE:- For "super" and "this" when you use in constructors always write them in the first line of your constructor code otherwise compiler will give error. </p></li> <li><p>Even when you do not extend MyClass here compiler will give call to constructor to super Object class which is the root class of every class you create. </p></li> </ol> <p>Case 2:- The use of "this". </p> <p>Constructors use "this" to refer to another constructor in the same class with a different parameter list.</p> <pre><code> public MyClass() { this(); } </code></pre> <p>So the above code will give compilation error "Recursive Constructor Invocation" as it is calling the same constructor and will end up in an infinite loop. To make this work you can instead write </p> <pre><code>public MyClass(String str){ System.out.println("constructor with arg "+ str); } public MyClass(){ this("Cons"); // note that "this" has to be at first line otherwise compiler gives error System.out.println("constructor with no arg"); } </code></pre> <p>Here you can see the importance of "this" in constructors. It is used to call constructors from another constructor in the same function.</p> <p>Case 3:- Use of "Super". Super is used to make a call to no-arg constructor of super call. Rest information is mentioned in Case 1 already.</p> <pre><code> public MyClass() { super(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload