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
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.
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 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.
There are two types of constructors in Java: default constructors and parameterized constructors.
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.
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.
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.
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.
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.
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 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.
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:
Finally, the displayDimensions method is called on each rectangle object to display their respective dimensions.
The key differences between a constructor and method in Java are elucidated below:
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.
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.
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:
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.
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.
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
+918045604032
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.