0
0
Javaprogramming~5 mins

Parameterized constructor in Java

Choose your learning style9 modes available
Introduction

A parameterized constructor lets you create an object with specific values right away. It helps set up the object exactly how you want it when you make it.

When you want to create a new object and give it initial details immediately.
When you want to avoid setting each property one by one after creating an object.
When you want to make sure an object always has certain values when it is created.
Syntax
Java
class ClassName {
    ClassName(type parameter1, type parameter2, ...) {
        // use parameters to set object properties
    }
}

The constructor name must be the same as the class name.

Parameters inside the parentheses let you pass values when creating an object.

Examples
This constructor takes a model name and year to set up a Car object.
Java
class Car {
    String model;
    int year;

    Car(String model, int year) {
        this.model = model;
        this.year = year;
    }
}
This constructor sets the name and age when creating a Person object.
Java
class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
Sample Program

This program creates a Book object with a title and author using a parameterized constructor, then prints the details.

Java
public class Book {
    String title;
    String author;

    // Parameterized constructor
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

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

    public static void main(String[] args) {
        Book myBook = new Book("The Java Guide", "Anna Smith");
        myBook.display();
    }
}
OutputSuccess
Important Notes

Using this keyword helps to distinguish between class fields and parameters with the same name.

If you do not define any constructor, Java provides a default no-argument constructor.

Summary

Parameterized constructors let you set object values when you create it.

They require parameters to pass data into the constructor.

Use this to refer to the current object's fields inside the constructor.