In this article, we will learn about default constructor in java, what it is, its syntax, definition with examples.
What is constructor in java
A constructor in java is a special method which has the same name as its class.
It is automatically called when we create an object of its class.
A constructor may or may not have any arguments.
A constructor that has arguments is also called parameterized constructor.
Constructor Example
Below is an example of constructor in java.
public class ConstructorDemo { private int id; public ConstructorDemo() { } /* * Parameterized constructor */ public ConstructorDemo(int id) { this.id = id; } }
Default Constructor
In the above example, we defined two constructors inside a class.
But, even if you do not define any constructor, the compiler automatically creates one, behind the scenes.
This constructor does not accept any arguments and is created automatically.
Hence it is called Default Constructor.
Default constructor definition
Definition of default constructor as per Java Language Specification(JLS) is
If a class contains no constructor declarations, then a default constructor is implicitly declared
Default constructor syntax
A default constructor is a method that is,
- of the same name as its class,
- has the same access specifier as its class, and
- does not accept any arguments.
Default constructor example
Consider below class
public class DefaultTest { }
Compile this class using java DefaultTest.java
command.
This will create a new file DefaultTest.class
Now, decompile this class file with command javap DefaultTest.class
and below is the output.
Compiled from "DefaultTest.java" public class DefaultTest { public DefaultTest(); }
Notice that we did not define any constructor in our class but it is present in the compiled class.
This is auto generated by the compiler and is called default constructor.
Tweaks
- A default constructor is ALWAYS a no-arg constructor.
- A default constructor will ONLY be generated if the class does not have any other constructor.
So, if you define a parameterized constructor, then default constructor will not be created. - You cannot see default constructor in your class, it is generated by the compiler.
- A default constructor has the same access specifier as its class.
If the class ispublic
, constructor ispublic
and so on. - Default constructor does not declare to throw any exception with
throws
.
That is all on default constructor in java.