CodeBlanks Logo Icon CodeBlanks

Parameterized constructor

Learn constructors that take parameters.

Parameterized constructor

A constructor can take parameters. Parameters are declared in parentheses and used in the body. This way, values are passed from outside when the instance is created; no manual assignment is needed.

Example: class Book { String title; Book(String t) { title = t; } }. Here Book(String t) takes a String parameter. When new Book("Java") is called, t becomes "Java" and is assigned to title. This approach finishes value assignment in one step; it is cleaner and safer.

Instantiation with parameters

When a parameterized constructor is called, values are written inside the parentheses. The value types must match the parameters. Multiple parameters are separated by commas and given in the same order.

Example: Book b = new Book("Java", 300);. Here two parameters exist: a string and an integer. The constructor must be declared as Book(String t, int p). Parameter order matters; the string comes first, then the integer. Wrong order causes a compile error.

Practice Add a parameterized constructor to Book

Define a class named Book. Add a String title field. Write a Book(String t) constructor; its body assigns title = t;. In main create an instance with new Book("Java") and print the title field.

Starter code

Main.java
// Define the Book class
// Add a parameterized constructor
// Instantiate and print in main

Sample solution

Main.java
class Book {
    String title;
    Book(String t) {
        title = t;
    }
    public static void main(String[] args) {
        Book b = new Book("Java");
        System.out.println(b.title);
    }
}

Expected output

Java

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the parameterized constructor parts

Term Meaning
Book Constructor name
String t Parameter
title = t Assignment
new Book("Java") Call

2 The constructor Book(String t) exists. Which call is valid?

  • new Book();
  • new Book("Java"); Correct answer
  • new Book(300);
  • Book("Java");

Explanation: New Book("Java"); — the parameter must be a String.

3 Complete the parameterized constructor body

Question
class Book {
    String title;
    Book(String t) {
        title = ____;
    }
}
Answer
class Book {
    String title;
    Book(String t) {
        title = t;
    }
}

Explanation: The parameter t is assigned to the title field.

All lessons in Intermediate