Default constructor (No-arg constructor)
A no-arg constructor doesn’t accepts any parameters, it instantiates the class variables with their respective default values (i.e. null for objects, 0.0 for float and double, false for Boolean, 0 for byte, short, int and, long).
There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.
Rules to be remembered
While defining the constructors you should keep the following points in mind.
A constructor does not have return type.
The name of the constructor is same as the name of the class.
A constructor cannot be abstract, final, static and Synchronized.
You can use the access specifiers public, protected & private with constructors.
Example
class NumberValue { private int num; public void display() { System.out.println("The number is: " + num); } } public class Demo { public static void main(String[] args) { NumberValue obj = new NumberValue(); obj.display(); } }
Output
The number is: 0
Example
public class Student { public final String name; public final int age; public Student(){ this.name = "Raju"; this.age = 20; } public void display(){ System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); } public static void main(String args[]) { new Student().display(); } }
Output
Name of the Student: Raju Age of the Student: 20