Default constructor in java class is the method with same name as class name and No parameters.
 

public class ConstructorClass {
 // Default Constructor
 public ConstructorClass(){
 }
}

 
It is Not mandate to have default constructor defined in a class, but exceptions is as below;
If you have constructor with field parameters and you still want to have default constructor then you need to explicitly define the default constructor.
 
Most common use of constructor is to enforce initial values are always set while creation of instance of a class itself.
 
Complete class ConstructorClass.java can be found below;

package com.basic;

/**
 * @author Niranjan
 *
 */
public class ConstructorClass {
	
	String name;
	String empID;
	
	public ConstructorClass(String nameValue, String empIDValue){
		name = nameValue;
		empID = empIDValue;
	}
	
	public ConstructorClass(String nameValue){
		name = nameValue;
		empID = "";
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ConstructorClass obj = new ConstructorClass("Niranjan","12345");
		
		System.out.println(obj.name);
		System.out.println(obj.empID);
	}
}

 
Refer YouTube tutorial with detailed explanation

 
For further reading refer Java Programming Category posts.

Default constructor in java class
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *