top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Parameterized Constructors in Java

Introduction 

A parameterized constructor in Java is a special constructor that allows you to initialize objects with values provided as parameters. Unlike a default constructor in Java, which has no parameters, a parameterized constructor enables you to customize the initialization of an object by passing specific values during object creation.

This powerful feature provides flexibility and control, allowing you to set the initial state of an object according to your requirements.

Overview

In this tutorial, we will explore the concept of parameterized constructors in Java, their syntax, and how they enhance the object creation process.

Constructors in Java   

Constructors in Java are essential for initializing objects. They are automatically invoked when objects are created and set initial values to the object's variables. Constructors share the class name and lack a return type.

Constructors are crucial in object-oriented programming as they guarantee proper object initialization. They encapsulate initialization logic, simplifying object creation and management in Java.

Types of Constructors in Java  

There are two types of constructors in Java: default constructors and parameterized constructors.

Default constructor (no-arg constructor)

The Java compiler automatically generates a default constructor, also called a no-arg constructor, when no other constructors are explicitly declared in a class. This unique constructor doesn't accept arguments and is provided to initialize objects with default values or set variables to their initial state.

The default constructor in Java is used to initialize objects with default values or set the variables to their default initial state. It is called automatically when an object is created using the new keyword without providing any arguments.

The default constructor can be explicitly defined by the programmer as well. It can perform additional initialization tasks beyond setting default values in such cases.

Parameterized constructor 

The programmer explicitly defines a parametrized constructor and accepts parameters during object creation. It allows you to customize the initialization process by passing specific values as arguments. 

With parameterized constructors, you can initialize object member variables with specific values, making the objects more tailored to your requirements.

Default Constructor in Java Examples

Example of Default Constructor

public class Circle {
    private double radius;

    // Default constructor
    public Circle() {
        radius = 1.0;  // Default value for radius
    }

    public static void main(String[] args) {
        Circle circle = new Circle();
        System.out.println("Radius: " + circle.radius);
    }
}

In this example, the Circle class represents a circle object with a radius field. The default constructor Circle() initializes the Circle object with a default value for the radius. Inside the constructor, the radius field is assigned the value of 1.0, which serves as the default value.

In the main method, an instance of circle is created using the default constructor new Circle(). The value of the radius field is then accessed and displayed using circle.radius, which will be the default value of 1.0.

Example of Default Constructor That Displays the Default Values

public class Book {
    private String title;
    private String author;

    // Default constructor
    public Book() {
        title = "Unknown";  // Default value for title
        author = "Anonymous";  // Default value for author
    }

    public void displayDetails() {
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
    }

    public static void main(String[] args) {
        Book book = new Book();
        book.displayDetails();
    }
}

In this example, the Book class represents a book object with title and author fields. The default constructor Book() initializes the Book object with default title and author field values. Inside the constructor, the title field is assigned the value of "Unknown" and the author field is assigned the value of "Anonymous", serving as the default values.

The displayDetails method is defined to display the values of the fields. In the main method, an instance of Book is created using the default constructor new Book(). The displayDetails method is then called on the book object to print the default values for the book's title and author.

Parameterized Constructor in Java Example

In this example, the Employee class represents a employee object with name and age fields. The parameterized constructor Employee(String name, int age) initializes the Employee object with specific values for the name and age fields. The constructor takes two parameters, name of type String and age of type int.

Inside the constructor, the this keyword is used to refer to the current object. The statement this.name = name; assigns the value of the name parameter to the name field of the current object. Similarly, this.age = age; assigns the value of the age parameter to the age field of the current object.

The displayDetails method is defined to display the values of the name and age fields. It simply prints the values using System.out.println().

In the main method, an instance of Employee is created using the parameterized constructor new Employee("Aritra Bandyopadhyay", 26). The provided values "Aritra Bandyopadhyay" and 26 are passed as arguments to the constructor, which initializes the name and age fields accordingly.

Finally, the displayDetails method is called on the employee object to display the details of the employee, including the name and age.

Why Parameterized Constructors Are Used   

A parameterized constructor in Java provides flexibility in initializing object member variables with values relevant to the specific instance being created. By passing arguments to the constructor, you can customize the object's initial state.

When using a parameterized constructor, you can define the required parameters, specify their types, and use them to assign values to the corresponding member variables within the constructor body.

Constructor Overloading in Java   

Constructor overloading in Java allows the creation of multiple constructors within a class, each with a different parameter list. This enables objects to be instantiated using different sets of arguments, providing flexibility in initialization. 

Overloaded constructors are differentiated by the number, order, and types of parameters they accept. When creating an object, the appropriate constructor is automatically invoked based on the provided arguments. 

Constructor overloading simplifies object creation by offering multiple ways to initialize objects without needing separate methods. It promotes code reusability and enhances the flexibility of object instantiation in Java.

Example of Constructor Overloading

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

    // Default constructor
    public Rectangle() {
        length = 0;
        width = 0;
    }

    // Parameterized constructor with one parameter
    public Rectangle(int side) {
        length = side;
        width = side;
    }

    // Parameterized constructor with two parameters
    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }

    public void displayDimensions() {
        System.out.println("Length: " + length);
        System.out.println("Width: " + width);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle();
        rectangle1.displayDimensions();

        Rectangle rectangle2 = new Rectangle(5);
        rectangle2.displayDimensions();

        Rectangle rectangle3 = new Rectangle(10, 8);
        rectangle3.displayDimensions();
    }
}

In this example, the Rectangle class represents a rectangle object with length and width fields. It demonstrates constructor overloading by providing multiple constructors with different parameter lists.

The default constructor Rectangle() creates a rectangle object with default dimensions. Inside the constructor, the length and width fields are initialized to 0.

The parameterized constructor Rectangle(int side) is used to create a square object where all sides have the same length. It takes one parameter side, and inside the constructor, both the length and width fields are assigned the value of the side.

The parameterized constructor Rectangle(int length, int width) is used to create a rectangle object with different lengths and widths. It takes two parameters, length, and width, and assigns the provided values to the corresponding fields.

The displayDimensions method is defined to display the rectangle's dimensions, i.e., the length and width. It simply prints the values using System.out.println().

In the main method, three instances of Rectangle are created using different constructors:

  • rectangle1 is created using the default constructor, resulting in a rectangle with 0 length and 0 width.

  • rectangle2 is created using the parameterized constructor with one parameter, passing a value 5. This creates a square object with a length and width of 5.

  • rectangle3 is created using the parameterized constructor with two parameters, passing values of 10 and 8. This creates a rectangle object with a length of 10 and a width of 8.

Finally, the displayDimensions method is called on each rectangle object to display their respective dimensions.

Difference Between Constructor and Method in Java   

The key differences between a constructor and method in Java are elucidated below:

Copy Constructor in Java

A copy constructor in Java allows creating a new object by copying the values of another object of the same class. 

The copy constructor takes an object of the same class as a parameter and initializes the new object's member variables with the values from the provided object. This can be a shallow copy, where the reference variables are copied, or a deep copy, where new instances are created for the member variables. 

It provides a convenient way to create an independent copy of an existing object. It ensures data integrity and can be used for object cloning and sharing tasks. It must be explicitly defined in the class and allows customization of the copying process.

Copying Values Without Constructor

In Java, you can copy values from one object to another without using a constructor by using various approaches, such as setter methods or cloning. Here is an example where we copy values from one object to another using setter methods:

(Person class / Person.java file)

public class Person {
    private String name;
    private int age;

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

(upGradTutorials class / upGradTutorials.java file)

public class upGradTutorials {
    public static void main(String[] args) {
        Person person1 = new Person();
        person1.setName("John");
        person1.setAge(30);

        Person person2 = new Person();
        copyValues(person1, person2);

        System.out.println("Person 1: Name - " + person1.getName() + ", Age - " + person1.getAge());
        System.out.println("Person 2: Name - " + person2.getName() + ", Age - " + person2.getAge());
    }

    public static void copyValues(Person source, Person destination) {
        destination.setName(source.getName());
        destination.setAge(source.getAge());
    }
}

In this example, we have a Person class with name and age fields, along with their respective getter and setter methods. In the upGradTutorials class, we create two instances of the Person class: person1 and person2. We set the name and age for person1 using its setter methods.

To copy the values from person1 to person2, we define a static method copyValues that takes the source object (person1) and the destination object (person2) as parameters. Inside the copyValues method, we use the setter methods of the destination object to set its name and age based on the values from the source object.

Finally, we print the values of person1 and person2 to verify that the values have been successfully copied.

Error Thrown by Default Constructor

When the default constructor throws an error, it typically means an issue during the object's initialization. This can occur for various reasons, such as:

  • Missing or incorrect initialization logic: If the default constructor contains an incorrect initialization code or missing some essential steps, it can result in an error.

  • Exception handling: If the default constructor throws an exception and there is no proper exception-handling mechanism, the error will be propagated, and the program may terminate or behave unexpectedly.

  • Dependencies or resource allocation: If the default constructor relies on other objects or resources that are not available or improperly initialized, it can cause errors.

Conclusion 

A parameterized constructor in Java enables customized object initialization by accepting specific values as arguments. They enhance flexibility and control in object creation. Mastering parameterized constructors is crucial for building robust Java applications. 

With that being said, enrolling in a course from upGrad can accelerate your learning journey by providing expert guidance, practical examples, and hands-on exercises to help you confidently utilize parameterized constructors and excel in Java programming.

FAQs

1. How can you write a parameterized constructor code in Java?

To write a parameterized constructor in Java, define a constructor in a class with one or more parameters and use them to initialize the object's member variables.

2. How can you parameterize in Java?

In Java, you can parameterize by specifying the data type and name of the parameter in the method or constructor declaration.

3. How is a parameterized constructor called?

A parameterized constructor is called automatically during object creation when the "new" keyword is used with the constructor, passing the required arguments based on the parameter list.

Leave a Reply

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