Parameterized Constructor in Java

Parameterized Constructor in Java

10 Sep 2024
Beginner
4.41K Views
9 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

Parameterized Constructor in Java: An Overview

Parameterized Constructors in Java are those kind of constructors that can take one or more parameters during the process of object creation. While we have constructors that are used to set initial values for the attributes of the object, parameterized constructors advances it by allowing the passing of arguments to the constructor when the object is created. In this Java tutorial, we'll learn about them in detail. To enhance your knowledge in Java, consider enrolling in our Java Full Stack Developer Course.

Constructors in Java

First of all, let us recall what are constructors in Java. Constructors are those special type of methods that are used to initialize objects of a class. Moreover, they have the same name as the class name and are invoked whenever an object of that specific class is created. Learn more about Constructors in Java and its types.

Read More - Top Java Interview Questions And Answers

Read More - Top Java Multithreading Interview Questions

What is a Parameterized Constructor

A Parameterized Constructor is a type of constructor that take one or more parameters when the object is created and also allows the developer to initialize the attributes of the object by providing values of their own interest. That is how parameterized constructors in Java give greater flexibility while initializing objects as the initial state of an object can be easily customized based on the specific values provided at the time of creation.

Syntax of Parameterized Constructor

The syntax of the Parameterized constructor in Java is as follows:

    public class MyClass {
    // Declare instance variables
    int number;
    String text;

    // Parameterized Constructor
    public MyClass(int num, String str) {
        // Initialize instance variables using constructor parameters
        number = num;
        text = str;
    }
}    

Here, 'MyClass' is a class with a parameterized constructor that takes two parameters that are- an integer 'num' and a string 'str'. Within the constructor, these parameters are used to initialize the instance variables 'number' and 'text' respectively.

Example Program:

To understand the Parameterized Constructor in Java better, here is a simple program in Java Compiler:
    public class Main {
    public static void main(String[] args) {
        // Create an object of MyClass using the parameterized constructor
        MyClass obj = new MyClass(10, "Hello");

        // Access object attributes
        System.out.println("Number: " + obj.number);
        System.out.println("Text: " + obj.text);
    }
}    

In the above example, while we create the object of 'MyClass', we pass '10' as the value of 'num' and '"Hello"' as the value of 'str'. These values are further used to initialize the attributes, 'number' and 'text', of the object.

Output

Number: 10
Text: Hello 

Why Parameterized Constructors are used?

Parameterized Constructors play a vital role in the initialization and customization of objects in Java programs. Some of its advantages are listed below:

  • Customization- With the help of parameterized constructors, you can easily customize the values while initializing objects based on the arguments provided.
  • Code Reusability- Parameterized constructors let you reuse the same constructor logic if you want to create an object with a different initial state.
  • Encapsulation and Data Integrity- They help maintain data integrity and prevent unauthorized access by encapsulating the initialization logic within the constructor promoting the OOPs concepts in Java.
  • Constructor Overloading- Parameterized constructors also support constructor overloading and lets you define multiple constructors with different parameter lists within the same class.
  • Clearer Object Creation- The setting of initial values of object attributes is more clear and concise at the moment of object creation, simplifying the code and making it more readable.

Default Constructor vs Parameterized Constructor

Default ConstructorParameterized Constructor
A default constructor is a type of constructor which is created by the compiler itself when no constructor is defined in the class.A parameterized constructor is provided by the developer with one or more than one parameters.
Object attributes are initialized with default values.Object attributes are initialized with specific values provided by the user.

Constructor Overloading

Construct overloading in Java refers to the ability to define multiple constructors with different parameter lists, within a class. This allows the developer to initialize objects in different ways at the time of object creation.

Example

    public class Rectangle {
    private int length;
    private int width;

    // Constructor with no parameters
    public Rectangle() {
        length = 0;
        width = 0;
    }

    // Constructor with one parameter (for square)
    public Rectangle(int side) {
        length = side;
        width = side;
    }

    // Constructor with two parameters (for rectangle)
    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }

    // Method to calculate area
    public int calculateArea() {
        return length * width;
    }

    public static void main(String[] args) {
        Rectangle square = new Rectangle(5); // Creating a square
        System.out.println("Area of the square: " + square.calculateArea());

        Rectangle rectangle = new Rectangle(4, 6); // Creating a rectangle
        System.out.println("Area of the rectangle: " + rectangle.calculateArea());
    }
}    

Here, we have a class 'Rectangle' which contains three constructors:

  • one constructor without parameters, that has initialized 'length' and 'width' to 0.
  • one has a parameter, that will create a square and set the value of 'length' and 'width' to same value.
  • another one has two parameters, that will create a rectangle and set the 'length' and 'width' to different values.

Now, the constructor will be called based on the parameters given to it.

Output

Area of the square: 25
Area of the rectangle: 24 
Summary
In this article, we learned how Parameterized Constructors played a major role during the time of object creation. You can explore more about them in Java Full Stack Developer Training to understand how parameterized constructors in Java can be used to our advantage.

FAQs

Parameterized Constructors are helpful in providing flexibility in initializing objects by allowing the developer to initialize object attributes with specific values passed as arguments at the time of object creation.

A default parameter constructor, also known as default constructor, is provided by the compiler by default if no constructor is defined. It initializes attributes of an object with default values.

A parameterized method in Java is a method that accepts one or more parameters and lets you pass values to the method when it is called. It helps the method to perform different operations based on the values provided.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this