Default and Parameterized Constructor Java Example Program


Definition

Default Constructor: A Constructor with no argument is called default Constructor
Parameterized Constructor: A Constructor with arguments is called Parameterized Constructor

Syntax

//Default Constructor
Class ConstructorExample {
	ConstructorExample (){
		//Do something
	}
}

//Parameterized Constructor
Class ConstructorExample {
    <datatype> variableName;

	ConstructorExample (<datatype> variableName){
            this.variableName = variableName;
		//Do something
	}
}

Default and Parameterized Constructor Example Program

public class DefaultAndParameterizedConstructor {
    public static void main(String[] args) {
        //Creating object of class using default constructor
        DefaultConstructorExample object1 = new DefaultConstructorExample();
        object1.doAddition();
        
        //Creating object of class using parameterized constructor
        ParameterizedConstructorExample object2 = new ParameterizedConstructorExample(100,200);
        object2.doAddition();
    }
}

class DefaultConstructorExample{
    int num1 = 5, num2 = 10, result;
    int doAddition(){
        result = num1+num2;
        System.out.println("This method is called using a default constructor");
        return result;
    }
}

class ParameterizedConstructorExample{
    int num1, num2, result;

    public ParameterizedConstructorExample(int num1, int num2) {
        this.num1 = num1;
        this.num2 = num2;
    }
    
    int doAddition(){
        result = num1+num2;
        System.out.println("This method is called using a parameterized constructor");
        return result;
    }
}

Sample Output

This method is called using a default constructor
This method is called using a parameterized constructor