Parameterized Constructor in Java

Parameterized Constructor in Java

29 Mar 2024
Beginner
286 Views
8 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

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 Certification 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.

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 Online Training to understand how parameterized constructors in Java can be used to our advantage.

FAQs

Q1. What is the advantage of using parameterized constructor?

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.

Q2. What is the default parameter constructor in Java?

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.

Q3. What is parameterized method in Java?

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
Live Training Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this