Java - Class Default Constructor

What is Default Constructor?

Java compiler adds a constructor to your class if you do not declare one.

The constructor added by the compiler is called the default constructor.

Syntax

The default constructor does not have any parameters.

The access level of the default constructor is the same as the access level of the class.

Example

Examples of Classes for Which a Default Constructor Is Added by the Java Compiler

Your Class                  Compiled Version of Your Class      Comments

public class T {            public class T {                    The compiler adds a default constructor with public access level.
}                              public T() {               
                               }                          
                            }                             

class T {                   class T {                           The compiler adds a default construct with
}                              T() {                            package-level access.
                               }                          
                            }                             
                                                              
public class T {            public class T {                     The T class already had a constructor. The
  T() {                       T() {                               compiler does not add any constructor.
  }                           }                            
}                           }                             
                                                              
public class T {            public class T {                     The T class already had a constructor. The
  public T(int x) {            public T(int x) {                   compiler does not add any constructor.
  }                            }                            
}                           }                             
                                                              
public class T {             public class T {                    The compiler adds a public default constructor for the T class
  private class Inner {         public T() {                     and a private default constructor for the Inner class.
  }                             }                                      
}                               private class Inner {                  
                                   private Inner(){                     
                                   }                          
                                }                            
                             }                             

Related Topic