View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Parameterized Constructors in Java

Updated on 19/03/20259,013 Views

Java Programming uses constructors as sections of code that build (construct) object state and value during object initialization. The constructor activates automatically during the creation of new objects with the new () statement. 

In Java a parameterized constructor functions by accepting specified parameters and enabling object initializations according to defined values. The parameterized constructor differs from the default constructor since it allows object creators to establish initial conditions through arguments during object instantiation. Parameters in constructors enable creators to set defaults while generating objects dynamically and this functionality applies to various fields. 

Enhance your Java programming skills with our Software Development courses and take your learning journey to the next level!

This article explores the ideas of Constructors in the Java programming language, especially the role of Parameterized Constructors in Java along with examples. 

Also Read: Understanding Parameterized Constructor in C++: Working and Examples

What is a Parameterized Constructor?

A Parameterized Constructor is a kind of constructor that accepts one or more parameters during object creation and enables the developer to set the object's attributes by supplying values of their choice. This is how Parameterized Constructors in Java offer increased flexibility during object initialization, as the initial state of an object can be readily tailored according to the specific values given at the moment of creation. 

A default constructor is a no-argument constructor that does not take any parameters. Parameterized constructors have one or multiple arguments. The primary role of the default constructor is to set default values for the objects that are created. 

A Java class will generate a default constructor if the programmer has not specified any constructor type in the class. The programmer must explicitly define the parameterized constructor. The primary purpose of developing a parameterized constructor is to set up objects with values or states defined by the programmer. During the object initialization process, the values of members can be set using parameterized constructors. 

Also Read: Private Constructor in Java: Introduction

Syntax and Basic Usage of Parameterized Constructors in Java

The syntax and basic usage of parameterized constructors in Java allow developers to initialize objects with specific values at the time of their creation. Unlike default constructors, parameterized constructors enable flexibility by accepting arguments that define an object's initial state. This section will explore how to define and use parameterized constructors effectively in Java programs.

General Syntax of a Parameterized Constructor

class ClassName {
// Instance variables (fields)
dataType variableName;

// Parameterized constructor
public ClassName(dataType parameter1, dataType parameter2, ...) {
// Initialize instance variables using the parameters
this.variableName = parameter1;
// Initialize other variables similarly
}
}

Key Components:

  • Constructor Name: The constructor's name is always identical to the class name (ClassName in this case). 
  • Parameters: The constructor takes in parameters that serve to initialize instance variables. 
  • this keyword: It is utilized to distinguish between instance variables and constructor parameters when they share the same name. 

Explanation of Constructor Parameters

In Java, the values provided to a constructor when an object of a class is instantiated are known as constructor parameters. These parameters enable you to set the instance variables of the object to particular values when the object is created. Constructor parameters are specified within the parentheses of the constructor's definition and are utilized to establish the initial state of an object upon its creation. 

Constructor parameters are the values you give when you instantiate an object via a constructor. 

These parameters are utilized to set up the instance variables (fields) of the class. 

Constructor Parameters Syntax: Constructor parameters resemble method parameters. They are specified in the constructor's signature (within the parentheses) and can be utilized to set values for instance variables.

class ClassName {
    // Instance variables
    dataType fieldName;
    // Parameterized constructor with parameters
    public ClassName(dataType param1, dataType param2) {
        // Using parameters to initialize fields
        this.fieldName = param1;
    }
}

dataType refers to the type of the parameter (e.g., int, String, etc.).

param1, param2, etc., are the names of the constructor parameters that you will pass when creating the object.

Importance of using parameterized constructors for object initialization (H3)

  • Guaranteeing a Valid Starting Point: 

Parameterized constructors enable you to set the initial conditions of an object by providing arguments when creating the object. This guarantees that objects are generated with the required values, preventing possible mistakes or unforeseen behavior in the future. 

  • Personalization and Adaptability: 

By taking parameters, constructors can be customized to generate objects with varying initial values, enhancing the flexibility and adaptability of your code to different situations. 

  • Refraining from Using Setter Methods: 

Employing parameterized constructors can remove the necessity for distinct setter methods to set object attributes, resulting in neater and more succinct code. 

  • Code Reusability: 

Parameterized constructors enhance code reusability by enabling the creation of objects with various initial states through the same constructor functionality. 

  • Data Consistency: 

By placing the initialization logic inside the constructor, you can support data integrity and avoid unauthorized access to object properties. 

  • Constructor Overloading: 

Parameterized constructors enable constructor overloading, permitting the definition of several constructors with varying parameter lists, which offers versatility in object creation. 

  • Enhanced Object Creation: 

Establishing initial values for object attributes is clearer and more succinct during object creation, streamlining the code and enhancing its readability.

Example: Creating and Using Parameterized Constructors

Let’s examine how a parameterized constructor functions in Java to set up object attributes. I will detail the procedure by using the example of a Book class that features a constructor with parameters to set the title and author attributes. 

Code:

class Book {
    // Instance variables (attributes)
    String title;
    String author;
    // Parameterized constructor
    public Book(String title, String author) {
        // Initializing instance variables using constructor parameters
        this.title = title;
        this.author = author;
    }
    // Method to display book details
    public void display() {
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
    }
}
public class Main {
    public static void main(String[] args) {
        // Creating a Book object using the parameterized constructor
        Book myBook = new Book("To Kill a Mockingbird", "Harper Lee");
        // Displaying the details of the book
        myBook.display();
    }
}

Step-by-Step Breakdown:

1. Class Definition and Instance Variables

class Book {
    // Instance variables (attributes)
    String title;
    String author;
}

Instance variables (title and author) are declared within the Book class. These are the attributes that will store data for an object of the class.

title: Stores the name of the book (e.g., "To Kill a Mockingbird").

author: Stores the name of the book’s author (e.g., "Harper Lee").

At this stage, when an object is created, these instance variables are empty (i.e., their default values are null for Strings).

2. The Parameterized Constructor (H4)


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

Constructor declaration: The public Book(String title, String author) is a constructor with parameters that accepts two arguments, title and author, to set the object's instance variables. 

Within the constructor, the this keyword is utilized to reference the object's instance variables (fields). The this.title denotes the object's instance variable title, while title (omitting this) indicates the constructor parameter. 

Initialization:

  • this.title = title;: This sets the current object's instance variable title to the value of the constructor parameter title. 
  • this.author = author;: In a similar manner, the constructor parameter author's value is allocated to the instance variable author of the present object. 

Utilizing this constructor, every new Book instance will be set up with particular values for title and author. 

3. Creating an Object Using the Constructor

Book myBook = new Book("To Kill a Mockingbird", "Harper Lee");

The new Book("To Kill a Mockingbird", "Harper Lee") part of the code is creating a new object of the Book class.

Step-by-step process:

Object Formation: 

  • The new keyword reserves memory for a new Book instance. 
  • The constructor "To Kill a Mockingbird" and "Harper Lee" is invoked to call the parameterized constructor. The constructor uses these values which are supplied through its parameter list. 

Parameter Setting: Within the constructor: 

  • The constructor uses the parameter to set the value "To Kill a Mockingbird". 
  • The Book object obtains its author value from the assignment "Harper Lee". 

Initialization of Instance Variables: 

  • The book object assigns "To Kill a Mockingbird" as the value for this.title. 
  • The Book object assigns Harper Lee as the value for this.author. 
  • After the constructor finishes its execution the Book object becomes absolutely prepared for use. 

4. After Initialization the Program can Retrieve and Present Set Data (H4)

myBook.display();

The myBook object triggers the activation of display() method. 

Through the display() method the program utilizes instance variables and displays their corresponding value. 

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

The execution will yield these lines because both the title and author instance variables were set to "To Kill a Mockingbird" and "Harper Lee."

Output: 

Title: To Kill a Mockingbird
Author: Harper Lee

The Role of the this Keyword in Parameterized Constructors

Java requires explicit clarification from you about which variable you mean whenever you have identical names between instance variables and parameters.

A parameter without "this" gets processed as a local variable instead of an instance variable according to Java. 

You use this keyword to specify to Java which instance variable belongs to the existing object. 

The constructor needs a transformation with the implementation of the this keyword. 

class Book {
    String title;  // Instance variable
    String author; // Instance variable
    // Parameterized constructor
    public Book(String title, String author) {
        this.title = title;  // 'this.title' refers to the instance variable 'title'
        this.author = author; // 'this.author' refers to the instance variable 'author'
    }
    public void display() {
        System.out.println("Title: " + title);  // Refers to the instance variable 'title'
        System.out.println("Author: " + author); // Refers to the instance variable 'author'
    }
}
public class Main {
    public static void main(String[] args) {
        // Creating a Book object using the parameterized constructor
        Book myBook = new Book("To Kill a Mockingbird", "Harper Lee");
        myBook.display();
    }
}

Explanation:

  • In this situation, we employ this.title = title; and this.author = author; to guarantee that we are referencing the instance variables (the fields title and author) of the present object. 
  • this.title indicates the instance variable, while title (wothout this) pertains to the parameter. In this manner, we are allocating the values provided to the constructor to the instance variables. 

Output: 

Title: To Kill a Mockingbird
Author: Harper Lee

At this point, the instance variables title and author are properly set with the values provided to the constructor. 

The this keyword refers to the present instance of the object. By utilizing this, you clearly indicate the instance variable of the object, even when its name coincides with a parameter or local variable. 

  • this.variableName: Indicates the instance variable (field) of the active object. 
  • variableName: Indicates the parameter or local variable within the method or constructor. 

Employing this eliminates the uncertainty and guarantees that you are indicating the instance variable, rather than the local variable. 

class Student {
    String name;  // Instance variable
    int age;      // Instance variable
    // Parameterized constructor
    public Student(String name, int age) {
        // Using 'this' to refer to the instance variables
        this.name = name;  // 'this.name' refers to the instance variable 'name'
        this.age = age;    // 'this.age' refers to the instance variable 'age'
    }
    public void display() {
        System.out.println("Name: " + name);  // Refers to the instance variable 'name'
        System.out.println("Age: " + age);    // Refers to the instance variable 'age'
    }
}
public class Main {
    public static void main(String[] args) {
        // Creating a Student object
        Student student = new Student("Alice", 22);
        student.display();
    }
}

Output

Name: Alice
Age: 22

Overloading Constructors with Parameters

In Java, constructors can be overloaded just like methods. Constructor overloading can be described as having multiple constructors with varying parameters, enabling each constructor to execute a distinct function. 

For example with Multiple Constructors

class Car {
    // Instance variables (fields)
    String model;
    int year;
    String color;
    // Default constructor (no parameters)
    public Car() {
        this.model = "Unknown";
        this.year = 2020; // Default year
        this.color = "Black"; // Default color
    }
    // Parameterized constructor with model and year
    public Car(String model, int year) {
        this.model = model;
        this.year = year;
        this.color = "Black"; // Default color
    }
    // Parameterized constructor with model, year, and color
    public Car(String model, int year, String color) {
        this.model = model;
        this.year = year;
        this.color = color;
    }
    // Method to display car details
    public void displayDetails() {
        System.out.println("Car Model: " + model);
        System.out.println("Year: " + year);
        System.out.println("Color: " + color);
    }
}
public class Main {
    public static void main(String[] args) {
        // Creating objects using different constructors
        
        // Using the default constructor
        Car car1 = new Car();
        car1.displayDetails();
        System.out.println();
        
        // Using the constructor with model and year
        Car car2 = new Car("Toyota Camry", 2021);
        car2.displayDetails();
        System.out.println();
        
        // Using the constructor with model, year, and color
        Car car3 = new Car("Honda Civic", 2022, "Blue");
        car3.displayDetails();
    }
}

Explanation:

Default Constructor (public Car()):

  • The public Car() constructor lacks any required parameter specifications. This constructor functions by setting default parameters for model, year and hue. 
  • The unknown model appears with a year set to 2020 and a color selection of Black. 
  • This public Car constructor takes model and year values through its parameters (public Car(String model, int year)). 
  • The constructor operates using model and year input parameters while automatically setting the color to "Black". 
  • The constructor accepts three parameters through its public Car(String model, int year, String color) signature. 
  • This class constructor requires model and year and color arguments which get stored in corresponding instance variables. 

Method displayDetails(): 

This method displays the specifics of the vehicle: model, year, and color. 

Output:

Car Model: Unknown
Year: 2020
Color: Black
Car Model: Toyota Camry
Year: 2021
Color: Black
Car Model: Honda Civic
Year: 2022
Color: Blue

Key Takeaways:

  • This instance features three constructors, each having distinct parameter lists. The available information determines the specific generation approach when creating objects. 
  • The default constructor becomes useful when details about the car remain unknown to you. 
  • The utilization of the constructor becomes possible with model and year inputs when that specific data is available. 
  • After acquiring complete model, year and color data you should use the constructor. 
  • The chosen constructor gets triggered by the parameters supplied when creating objects. The constructor that accepts both model and year launches when using new Car("Toyota Camry", 2021), but new Car("Honda Civic", 2022, "Blue") runs the version with all three arguments passed to it. 

Several direct applications exist where constructor overloading proves its practical efficiency: 

  • The ability to input objects with various data through constructor overloading proves ideal when initializing records consisting of different information blocks including student and employee details. 
  • Framework and API developers utilize constructor overloading for their object initialization process to allow users various options of data entry in object creation. 
  • Different configuration objects become possible through constructor overloading because developers can specify setup options ranging from default to partial to complete configurations which makes the objects operable across varying environments. 
  • Managing diverse user input: For applications that need to process information in various formats (such as dates, addresses, user profiles), constructor overloading can offer several methods to initialize objects based on the data at hand. 
  • Handling database entities: In database management, constructor overloading aids in initializing entity objects with different amounts of parameters, facilitating adaptable mapping between data models and database tables. 

Also Read: Constructor Overloading in Java: Explanation, Benefits & Examples

Parameterized Constructors and Inheritance

In Java, while dealing with inheritance, a subclass may also possess parameterized constructors. When a subclass contains a parameterized constructor, it does not automatically receive the constructors from its superclass; however, it can invoke the superclass constructor (including those that are parameterized) by utilizing the super() keyword. 

How Subclasses Utilize Parameterized Constructors

A subclass may possess its constructor with parameters. 

If a parameterized constructor exists in the superclass, the subclass has to explicitly invoke the superclass constructor with super() when the constructor is necessary. 

If the superclass includes a default constructor (a constructor without parameters), it is automatically invoked when a subclass object is instantiated, unless a different constructor is explicitly called with super(). 

Employing super() to Invoke the Parent Class Constructor

Let's examine a code example in which we utilize super() to invoke the parent class's constructor from the child class: 

class Animal {
    String name;
    int age;
    // Constructor in the parent class (Animal)
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("Animal class constructor called");
    }
    // Method to display animal details
    public void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}
class Dog extends Animal {
    String breed;
    // Constructor in the child class (Dog)
    public Dog(String name, int age, String breed) {
        // Calling the parent class constructor using 'super()'
        super(name, age);  // This calls Animal's parameterized constructor
        this.breed = breed;
        System.out.println("Dog class constructor called");
    }
    // Method to display dog details, overriding the parent class method
    @Override
    public void display() {
        super.display();  // Calling the parent class display method
        System.out.println("Breed: " + breed);
    }
}
public class Main {
    public static void main(String[] args) {
        // Creating a Dog object using the constructor of the Dog class
        Dog dog = new Dog("Buddy", 5, "Golden Retriever");
        
        // Displaying the details of the Dog object
        dog.display();
    }
}

Explanation:

Class Animal (Parent Class):

  • The Animal class enables constructor definition public Animal(String name, int age) to set name and age values while generating a specific message. 
  • The display() function demonstrates all animal details consisting of name and age. 

Class Dog (Child Class): 

  • The Dog class extends the Animal class by incorporating its own Dog(String name, int age, String breed) constructor. 
  • The Dog constructor starts by calling the parent class constructor with the parameters name and age through super(name, age). The parameters name and age travel from the child class to its parent class (Animal). 
  • The Dog constructor accepts unique values for breed and offers an additional announcement. 
  • The constructive call to the parent class occurs through the statement super(name, age). 
  • As part of the Dog constructor we use super(name, age) to execute the parameterized constructor of Animal for setting the name and age variables. 
  • If the Animal class lacks a default constructor, omitting super(name, age) will lead to a compilation error. 

Method Overriding: 

  • The Dog class modifies the display() method to include the display of the breed field. 
  • We utilize super.display() to invoke the display() method from the Animal class to output the name and age attributes. 

Output

Animal class constructor called
Dog class constructor called
Name: Buddy
Age: 5
Breed: Golden Retriever

Constructor Chaining

Constructor chaining involves invoking one constructor from another constructor, whether within the same class or from a superclass. 

super() is a component of constructor chaining. The subclass constructor first invokes the parent constructor to set up the inherited fields, and afterward, it carries out its initialization.

Difference Between Constructor and Method in Java

The table below provides a comparison between constructors and methods in Java. Both play crucial roles in object-oriented programming, but they serve different purposes. This table highlights their key differences in terms of purpose, usage, and behavior to help you better understand their roles in Java programming.

Feature

Constructor

Method

Purpose

Initializes an object when it is created.

Defines the behavior of the object.

Name

Same as the class name.

Can have any name, except class name.

Return Type

Does not have a return type (not even void).

Must have a return type (or void).

Overloading 

Can be overloaded (multiple constructors).

Can be overloaded (multiple methods).

Invocation

Automatically called during object creation.

Called explicitly on the object.

Object Creation

Responsible for creating and initializing the object.

Operates on an already created object.

Inheritance

Cannot be inherited.

Can be inherited by subclasses.

Default Behavior

If not defined, a default constructor is provided.

No default method is provided.

Common Mistakes and Best Practices

Common Mistakes:

  • Failing to Set Up Attributes: 

The lack of initialization in constructor parameters may produce NullPointerException errors along with unexpected system responses. 

  • Utilizing Excessive Parameters: 

míters added to construction methods can make them more difficult to understand during maintenance work. You should use the Builder pattern or combine multiple parameters into a single object structure. 

  • Ineffective Use of Constructor Chaining: 

When constructor chaining involves this() or super(), unauthorized code can be produced from incorrect usage. Each routine initialization process should be handled within a single constructor. 

  • Not Verifying Parameters: 

Failure to validate parameters will produce objects with improper states. The proper verification of all parameters is necessary to prevent unexpected errors. 

  • Omitting a Default Constructor: 

Constructors that use parameters should be supplemented with default constructors because they enhance program flexibility. 

  • Intricate Functions in Constructors: 

Object initialization forms the essential responsibility of constructors and they should limit complexity and number of responsibilities. 

Best Practices:

The following guidelines provide structured methods when using constructor overloading techniques in Java programming. 

  • Make constructors clear and significant: 

Every constructor needs to include specific initialization purposes to ensure developers can follow the intended goal. 

  • Steer clear of excessive strain: 

A large number of overloaded constructors makes code maintenance extremely complex. Sure! The following text needs paraphrasing according to your instructions. 

  • Utilize comments for intricate logic: 

Wear remarks to explain complex logic within constructors since they improve comprehension. 

  • Guarantee constructor coherence: 

The different overloaded constructors should execute equivalent functions to maintain consistency within object initializatio procedures. 

  • Utilize default values whenever feasible: 

Default values in constructors help create objects with less effort and fewer parameters in the creation process. 

Common Interview Questions on Parameterized Constructors in Java

Q: What occurs if you fail to specify a constructor in a class? 

A: A class without explicit constructors receives built-in default no-parameter constructor which uses default value settings (null for objects and zero for integers). Implementing any constructor in the class will disable the default constructor unless you explicitly place a definition for it. 

Q: Is it possible for a class to have several parameterized constructors? 

A: A class can obtain multiple parameterized constructors through the use of constructor overloading. A class can provide each constructor with its own set of parameters to allow objects initialization through different approaches. 

Q: Is it possible to invoke one constructor from another constructor within the same class? 

A: There exist two methods for naming this phenomenon in programming - constructor chaining. You can call one constructor from another constructor through the this() keyword in the same class. This enables you to utilize constructor code again. 

Q: Is it possible to declare a constructor as final or abstract? 

A: No, it is not possible to declare constructors as final or abstract. A constructor serves to initialize an object, and it cannot be inherited or overridden (similar to an abstract method), nor can it be finalized. 

Q: Is it possible for a constructor to return a value? 

A: No, a constructor is not able to return a value. It lacks a return type, not even void. Its only aim is to set up the object. 

Also Read: Top 130+ Java Interview Questions & Answers

Practice Exercise Suggestion

Exercise 1: Write a Java class Book with a parameterized constructor to initialize title and author

Here's a simple Java class Book with a parameterized constructor to initialize the title and author fields:

Code

class Book {
    String title;
    String author;
    // Parameterized constructor to initialize title and author
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
    // Method to display book details
    public void displayBookDetails() {
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
    }
    public static void main(String[] args) {
        // Creating a Book object using the parameterized constructor
        Book myBook = new Book("The Alchemist", "Paulo Coelho");
        // Displaying the details of the book
        myBook.displayBookDetails();
    }
}

Explanation 

Class Definition: 

The Book class contains two instance variables: author and title. 

Parameterized Constructor: 

The constructor public Book(String title, String author) sets the title and author of the book using the values provided when the object is created. 

Technique for Showing Book Information: 

The displayBookDetails() function outputs the title and author to the console. 

Primary Approach: 

In the main() method, a Book instance named myBook is instantiated with the parameterized constructor, providing "The Alchemist" for the title and "Paulo Coelho" for the author. 

The displayBookDetails() function is subsequently invoked to show the details of the book.

Output:

Title: The Alchemist
Author: Paulo Coelho

Exercise 2: Implement a class BankAccount where the constructor initializes the account holder’s name and balance.

Here's a Java class BankAccount where the constructor initializes the account holder's name and balance:

Code

class BankAccount {
    String accountHolderName;
    double balance;
    // Parameterized constructor to initialize account holder's name and balance
    public BankAccount(String accountHolderName, double balance) {
        this.accountHolderName = accountHolderName;
        this.balance = balance;
    }
    // Method to deposit money into the account
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: " + amount);
        } else {
            System.out.println("Deposit amount must be positive.");
        }
    }
    // Method to withdraw money from the account
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrew: " + amount);
        } else if (amount > balance) {
            System.out.println("Insufficient balance.");
        } else {
            System.out.println("Withdraw amount must be positive.");
        }
    }
    // Method to display account details
    public void displayAccountDetails() {
        System.out.println("Account Holder: " + accountHolderName);
        System.out.println("Balance: " + balance);
    }
    public static void main(String[] args) {
        // Creating a BankAccount object using the parameterized constructor
        BankAccount account = new BankAccount("Alice", 5000.0);
        // Display account details
        account.displayAccountDetails();
        // Depositing money
        account.deposit(1500.0);
        // Withdrawing money
        account.withdraw(2000.0);
        // Display updated account details
        account.displayAccountDetails();
    }
}

Explanation:

Instance Variables:

The BankAccount class contains two instance variables: 

  • accountHolderName: for saving the name of the account holder. 
  • balance: to maintain the account's balance. 

Constructor with Parameters:

The constructor public BankAccount(String accountHolderName, double balance) serves to set the accountHolderName and balance during the object's creation. 

Procedures: 

deposit(double amount): Increases the account balance when the amount is greater than zero. 

withdraw(double amount): Subtracts funds from the balance if the amount is legitimate and less than or equal to the available balance. 

showAccountInfo(): Shows the account owner’s name and the existing balance. 

Primary Approach: 

In the main() method, a BankAccount instance called account is instantiated using the parameterized constructor, setting it up with the name "Alice" and an initial balance of 5000.0. 

The methods deposit() and withdraw() are invoked to modify the balance. 

Ultimately, the revised account information is shown. 

Output:

Account Holder: Alice
Balance: 5000.0
Deposited: 1500.0
Withdrew: 2000.0
Account Holder: Alice
Balance: 4500.0

Exercise 3: Modify the Student class to include a constructor that accepts only name and sets a default age.

To change the Student class so that it has a constructor that takes just the name and assigns a default age, you can follow these steps. If the age is not given, the default value can be assigned to a specific number, such as 18. 

Code

class Student {
    String name;
    int age;
    // Constructor that accepts only name and sets a default age
    public Student(String name) {
        this.name = name;
        this.age = 18; // Default age
    }
    // Method to display student details
    public void displayStudentDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
    public static void main(String[] args) {
        // Creating a Student object using the constructor with only name
        Student student1 = new Student("John");
        // Displaying student details
        student1.displayStudentDetails();
    }
}

Explanation:

The constructor public Student(String name) takes the student's name as an argument and assigns the age a default value of 18. 

Within the constructor, the age is clearly assigned as 18, which serves as the default age when solely the name is given during the creation of the object. 

Technique for Presenting Information: 

The displayStudentDetails() function is utilized to output the student's name and age to the console.

Primary Approach: 

A Student object named student1 is instantiated using the constructor that takes only the name, with the default age of 18 assigned automatically. 

The displayStudentDetails() function is invoked to present the details of the student. 

Output:

ame: John
Age: 18

How upGrad Can Help You

If you want to enhance your understanding of Java and programming topics such as Parameterized Constructors in Java, or if you're prepared to elevate your skills in Java, it is strongly recommended that you check out upGrad's courses. They provide a diverse selection of industry-specific programs that deliver hands-on experience to assist you in creating real-world projects and acquiring practical skills. 

Some relevant courses that can interest you:

Regardless of whether you’re new to the field or aiming to improve your current abilities, upGrad's engaging learning platform can assist you with extensive coursework, live sessions, and mentorship. Their method of learning through projects guarantees that you utilize your knowledge in practical situations, equipping you for genuine challenges in the tech sector. 

By enrolling in upGrad's programs, you'll gain access to: 

  • Skilled educators with numerous years of practical experience. 
  • Hands-on projects to engage in that enhance your portfolio. 
  • Adaptable learning timetables to suit your way of life. 
  • Opportunities for networking with colleagues and industry experts. 

Therefore, if you're truly committed to progressing in your career, make sure not to miss this opportunity! For more information visit your nearest upGrad center.

Similar Reads:

FAQs 

1. Can a class have multiple constructors?

Yes, a class can have multiple constructors, as long as each constructor has a unique signature (different number or type of parameters). This is known as constructor overloading.

2. What is constructor overloading?

Constructor overloading allows a class to have multiple constructors with the same name but different parameter lists, enabling flexible object creation and initialization in various ways.

3. How do you call a parameterized constructor?

To call a parameterized constructor, you simply use the new keyword followed by the class name and the necessary arguments within parentheses, matching the constructor's parameter list.

4. What is the role of the this keyword in constructors?

In the context of constructors, the this keyword refers to the current object being created and is used to access its members (variables and methods) or to call other constructors within the same class.

5. Can constructors be private in Java?

In Java, you can declare a constructor as private. By declaring the constructor of a class as private, you can not create an object of that class. To declare the constructor as private, you can use the private access specifier. We generally use a private constructor in a Singleton class.

6. What happens if a class only has a parameterized constructor and no default constructor?

If a class only has a parameterized constructor and no default constructor, you cannot create an object of that class using the default constructor (without arguments) and will receive a compilation error.

7. How do parameterized constructors impact inheritance?

When a base class has a parameterized constructor, derived classes must either define their own constructors to call the base class's constructor using super() or base() (depending on the language), or the compiler will not automatically provide a default constructor, leading to errors.

8. Can a constructor call another constructor in the same class?

Yes, a constructor can call another constructor in the same class, a process known as constructor chaining, using the this() keyword.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.