For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
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
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
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.
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:
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.
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.
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.
Employing parameterized constructors can remove the necessity for distinct setter methods to set object attributes, resulting in neater and more succinct code.
Parameterized constructors enhance code reusability by enabling the creation of objects with various initial states through the same constructor functionality.
By placing the initialization logic inside the constructor, you can support data integrity and avoid unauthorized access to object properties.
Parameterized constructors enable constructor overloading, permitting the definition of several constructors with varying parameter lists, which offers versatility in object creation.
Establishing initial values for object attributes is clearer and more succinct during object creation, streamlining the code and enhancing its readability.
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.
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:
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).
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:
Utilizing this constructor, every new Book instance will be set up with particular values for title and author.
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:
Parameter Setting: Within the constructor:
Initialization of Instance Variables:
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
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:
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.
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
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()):
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:
Several direct applications exist where constructor overloading proves its practical efficiency:
Also Read: Constructor Overloading in Java: Explanation, Benefits & Examples
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.
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().
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):
Class Dog (Child Class):
Method Overriding:
Output
Animal class constructor called
Dog class constructor called
Name: Buddy
Age: 5
Breed: Golden Retriever
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.
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:
The lack of initialization in constructor parameters may produce NullPointerException errors along with unexpected system responses.
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.
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.
Failure to validate parameters will produce objects with improper states. The proper verification of all parameters is necessary to prevent unexpected errors.
Constructors that use parameters should be supplemented with default constructors because they enhance program flexibility.
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.
Every constructor needs to include specific initialization purposes to ensure developers can follow the intended goal.
A large number of overloaded constructors makes code maintenance extremely complex. Sure! The following text needs paraphrasing according to your instructions.
Wear remarks to explain complex logic within constructors since they improve comprehension.
The different overloaded constructors should execute equivalent functions to maintain consistency within object initializatio procedures.
Default values in constructors help create objects with less effort and fewer parameters in the creation process.
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
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
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:
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
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
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:
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:
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.
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.
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.
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.
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.
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.
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.
Yes, a constructor can call another constructor in the same class, a process known as constructor chaining, using the this() keyword.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.