Default constructor in Java

1.4

Like C++, Java automatically creates default constructor if there is no default or parameterized constructor written by user, and (like C++) the default constructor automatically calls parent default constructor. But unlike C++, default constructor in Java initializes member data variable to default values (numeric values are initialized as 0, booleans are initialized as false and references are initialized as null).

For example, output of the below program is

0
null
false
0
0.0

// Main.java
class Test {
   int i;
   Test t;
   boolean b;
   byte bt;
   float ft;
}

public class Main {
    public static void main(String args[]) {
      Test t = new Test(); // default constructor is called.
      System.out.println(t.i);
      System.out.println(t.t);
      System.out.println(t.b);
      System.out.println(t.bt);
      System.out.println(t.ft);
    }
}

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

References:
http://leepoint.net/notes-java/oop/constructors/constructor.html

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.4 Average Difficulty : 1.4/5.0
Based on 40 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.