Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Parameterized Constructor in Java?
2.1.
Syntax of Parameterized Constructor in Java
2.2.
Why Parameterized Constructors are Used?”
3.
Sample Examples
3.1.
Example 1
3.2.
Java
3.3.
Example 2
3.4.
Java
3.5.
Example 3
3.6.
Java
3.7.
Example 4
3.8.
Java
4.
Purpose of Parameterized Constructor in Java
5.
Differences Between Default Constructor and Parameterized Constructor in Java
6.
Frequently Asked Questions
6.1.
What is parameterized constructor in Java?
6.2.
What is the advantage of using parameterized constructor?
6.3.
What is parameterized method in Java?
6.4.
Q. How do you declare parameterized constructors with examples?
7.
Conclusion
Last Updated: Apr 20, 2024
Easy

Parameterized Constructor in Java

Author Sinki Kumari
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Parameterized constructors in Java define the initial state of an object by requiring one or more arguments during initialization. The access modifier of a constructor in Java matches the access modifier of its class for "public" and "default" access.

Parameterized constructor in java

This blog will discuss the Parameterized Constructor in Java in detail. Let's start without wasting time.

Also see, Duck Number in Java

What is a Parameterized Constructor in Java?

The constructor is said to be a parameterized constructor if the object contains a number of parameters or arguments. The arguments must be passed by the user explicitly. 

For example, If we wish to set our own values in the class's object fields, we should use a parameterized constructor.

Syntax of Parameterized Constructor in Java

In Java, a parameterized constructor is a constructor that takes one or more parameters. The syntax for declaring a parameterized constructor is:

ClassName(parameter1, parameter2, ...) {
  // constructor body
}

Here, ClassName is the name of the class, and parameter1, parameter2, etc., are the parameters accepted by the constructor. 

Why Parameterized Constructors are Used?”

When an object is declared, it is used to initialize it with values that the user passes as parameters.  Java's parametrized constructor allows user initialization of the object at the time of creation.

This makes it possible to initialize different objects with different values as needed, allowing for customisation and flexibility in object initialization. Because parameterized constructors enable objects to be initialized with different states according to the specific needs of the application or user, they make it easier to create more flexible and reusable classes. This improves Java code's general readability, maintainability, and usability.

Let's understand this better by an example.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Sample Examples

We will take a few examples so that the concept will be clear for you. Let's start.

Example 1

  • Java

Java

class CodingNinjas {
   // Initializing global variables
   String n;

   // Constructor
   CodingNinjas(String name) {
       n = name;
       System.out.println("My name is "+name);
   }
   public static void main(String[] args) {
       // Creating an object
       CodingNinjas myObj = new CodingNinjas("Ninja");
   }
}


Output:

Output

Explanation:

In the above example, 

  • We first initialize a global variable, n, of the string type. 
     
  • In the main method, we created an object named myObj and passed the input string value as an argument.
     
  • Then, we created a parameterized constructor that takes an argument as input and prints the value of n.
     

We can also pass more than one argument while creating an object. Let's take an example of this.

Example 2

  • Java

Java

class CodingNinjas {
   // Initializing global variables
   String n;
   String s;

   // Constructor
   CodingNinjas(String name, String sport) {
       n = name;
       s = sport;
       System.out.println("My name is "+name);
       System.out.println("My favourite sport is "+sport);
   }
   public static void main(String[] args) {
       // Creating an object
       CodingNinjas myObj = new CodingNinjas("Ninja", "Cricket");
   }
}


Output:

Output

Explanation:

In the above example, 

  • We have two global variables of the same data type, which is a string. The name of the first variable is n which represents the name, and the second variable is s representing the sport.
     
  • In the main method, we created an object with the name myObj and passed both the inputs of the string type as an argument.
     
  • Then, we created a parameterized constructor that takes two arguments as input and prints the value of n and s.

Example 3

Now, you must be thinking about whether we can give two arguments with different data types in an object. Let's find out the solution in this example.

  • Java

Java

class CodingNinjas {
   // Initializing global variables
   String n;
   String s;
   int a;

   // Constructor
   CodingNinjas(String name, String sport, int age) {
       n = name;
       s = sport;
       a = age;
       System.out.println("My name is "+name);
       System.out.println("My favourite sport is "+sport);
       System.out.println("I am "+age+ " years old");
   }
   public static void main(String[] args) {
       // Creating an object
       CodingNinjas myObj = new CodingNinjas("Ninja", "Cricket", 23);
   }
}


Output:

Output

Explanation:

In the above example,

  • We took three global variables, two variables of string type and one of the integer type.
     
  • In the main method, we created an object with the name myObj and passed all three inputs of the string and integer type as an argument.
     
  • Then, we created a parameterized constructor that takes three arguments as input and prints the value of n, s and a, which means the name, sport, and age.

Example 4

We have seen three types of examples, but have you thought about what will happen if we do not pass any arguments in parameterized constructor while creating the objects? Let's find out.

  • Java

Java

class CodingNinjas {
   // Initializing global variables
   String n;
   String s;
   int a;

   // Constructor
   CodingNinjas(String name, String sport, int age) {
       n = name;
       s = sport;
       a = age;
       System.out.println("My name is "+name);
       System.out.println("My favourite sport is "+sport);
       System.out.println("I am "+age+ " years old");
   }
   public static void main(String[] args) {
       // Creating an object
       CodingNinjas myObj = new CodingNinjas();
   }
}


Output:

Output


Explanation:

As you can see in the above example, the program will show an error saying actual and formal argument lists differ in length. Hence, we have to give proper arguments while running the program.

Also read, Swap Function in Java

Purpose of Parameterized Constructor in Java

If the programmer does not define any type of constructor in class, Java provides default constructor. The parameterized constructor must be explicitly defined by the programmer. The fundamental goal of writing a parameterized constructor is to initialize objects with programmatically defined states or values. The values of members can be assigned while object is being initialized using parameterized constructors.

Parameterized constructors allow objects to be initialized differently based on demands of different areas of your program or on user input. They make it clear what values are necessary to form an object and what those values represent, which improves code readability. This makes the code more self-documenting and understandable.

Differences Between Default Constructor and Parameterized Constructor in Java

Default ConstructorParameterized Constructor
Provided by the compiler if no other constructor is defined.Constructor with one or more parameters.
NO parameters.One or more parameters.
The purpose is to initialize instance variables with default values.The purpose of a parameterized constructor is to assign user-wanted specific values to the instance variables of different objects.

Example: public CodingNinjas() {

}

Example: public CodingNInjas(int x, String y) 

{

this.x = x; 

this.y = y; 

}

Frequently Asked Questions

What is parameterized constructor in Java?

The constructor is said to be a parameterized constructor if the object contains a number of parameters or arguments. The arguments must be passed by the user explicitly. 

What is the advantage of using parameterized constructor?

Parameterized constructors enable objects to be initialized with different states according to the specific needs of the application or user, they make it easier to create more flexible and reusable classes. This improves Java code's general readability, maintainability, and usability.

What is parameterized method in Java?

When a Java method is called with parameters, data can be provided into it during execution. This is known as a parameterized method.

Q. How do you declare parameterized constructors with examples?

To declare a parameterized constructor in Java, specify parameters within parentheses after the constructor's name. Here's an example:

public class CodingNinjas {    int x;    public  CodingNinjas(int val) {        x = val;    } }

In this example, the parameterized constructor accepts an integer value and assigns it to the 'x' instance variable.

Conclusion

This article discusses the topic of the Parameterized Constructor in Java in detail. We have seen the definition and four types of examples, including one, two, and three arguments of the same and different data types. 

We hope this blog has helped you enhance your knowledge of the Parameterized Constructor in Java. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
Default Constructor in Java
Next article
Copy Constructor in Java
Live masterclass