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
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
A constructor in Java is a special method that initializes objects when created. It shares the same name as the class and contains no return type. Each time you create a new object using the new keyword, a constructor executes. Constructors initialize the state of an object with proper field values automatically.
They provide a clean and efficient way to assign initial values for attributes. No object in Java can exist without being properly initialized by constructors. Understanding constructors is crucial for writing effective object-oriented programs in Java applications.
Constructors prevent objects from existing in invalid or incomplete states during runtime. They ensure that all necessary data members have appropriate values before object usage. The proper implementation of constructors helps maintain object integrity throughout program execution. If you're interested in mastering Java constructors, consider exploring online Software Engineering courses today.
A constructor in Java is a block of code similar to a method that is called when an instance of an object is created. Unlike regular methods, constructors have the same name as the class they belong to. The constructor in Java doesn't have an explicit return type. When you instantiate a class using the new operator, the constructor is automatically invoked.
public class Employee {
// Fields
private String name;
private int employeeId;
// Constructor in Java
public Employee(String name, int employeeId) {
this.name = name;
this.employeeId = employeeId;
}
// Display employee details
public void displayInfo() {
System.out.println("Employee ID: " + employeeId);
System.out.println("Employee Name: " + name);
}
public static void main(String[] args) {
// Creating an employee object using constructor
Employee emp = new Employee("John Doe", 1001);
emp.displayInfo();
}
}
Output:
Employee ID: 1001
Employee Name: John Doe
In the example above, Employee(String name, int employeeId) is a constructor in Java. It initializes the name and employeeId fields when a new Employee object is created.
Enhance your abilities through these best-in-class courses/certifications.
The primary use of a constructor in Java is to initialize the newly created object. Constructors provide a way to set initial values for object attributes. Here are the main uses of a constructor in Java:
Let's see an example of the use of constructor in Java:
public class BankAccount {
private String accountNumber;
private double balance;
// Constructor in Java
public BankAccount(String accountNumber, double initialDeposit) {
this.accountNumber = accountNumber;
// Enforcing a business rule during initialization
if (initialDeposit < 500) {
this.balance = 500; // Minimum balance requirement
System.out.println("Initial deposit must be at least $500. Setting minimum balance.");
} else {
this.balance = initialDeposit;
}
}
public void displayInfo() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Current Balance: $" + balance);
}
public static void main(String[] args) {
// Creating account with sufficient initial deposit
BankAccount account1 = new BankAccount("AC001", 1000);
account1.displayInfo();
// Creating account with insufficient initial deposit
BankAccount account2 = new BankAccount("AC002", 300);
account2.displayInfo();
}
}
Output:
Account Number: AC001
Current Balance: $1000.0
Initial deposit must be at least $500. Setting minimum balance.
Account Number: AC002
Current Balance: $500.0
In this example, the constructor enforces a minimum balance rule during object creation.
There are several reasons why we use constructors in Java:
Why we use constructor in Java becomes clear when we consider alternatives. Without constructors, we would need separate initialization methods. These methods might be forgotten or called in the wrong order. Constructors eliminate these risks by combining object creation and initialization.
Java supports several types of constructors, each serving different purposes. Understanding the types of constructors in Java helps developers choose the right approach for their specific requirements.
A default constructor in Java is a constructor that has no parameters. If you don't define any constructor in your class, the Java compiler automatically inserts a default constructor. This automatically generated constructor is called the implicit default constructor.
What is default constructor in Java? It's a constructor that:
Here's an example of default constructor in Java:
public class Student {
private String name;
private int age;
// Default constructor in Java (explicitly defined)
public Student() {
name = "Unknown";
age = 0;
}
// Methods
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
// Creating object using default constructor
Student student = new Student();
student.displayInfo();
}
}
Output:
Name: Unknown
Age: 0
If you don't define the default constructor as shown above, Java will provide an implicit one:
// This is how the compiler-generated default constructor would look
public Student() {
// Empty body
}
Key points about default constructor in Java:
A parameterized constructor in Java accepts one or more parameters. It provides a way to initialize an object with specific values during creation. Parameterized constructors are essential when you need objects with different initial states.
public class Rectangle {
private int length;
private int width;
// Parameterized constructor in Java
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public int calculateArea() {
return length * width;
}
public static void main(String[] args) {
// Creating object with specific values
Rectangle rectangle = new Rectangle(10, 5);
System.out.println("Rectangle dimensions: " + rectangle.length + " x " + rectangle.width);
System.out.println("Area: " + rectangle.calculateArea());
}
}
Output:
Rectangle dimensions: 10 x 5
Area: 50
Benefits of parameterized constructors:
A copy constructor in Java creates a new object as a copy of an existing object. Unlike C++, Java doesn't provide a built-in copy constructor. However, we can create our own copy constructor in Java.
The copy constructor in Java:
Here's an example of copy constructor in Java:
public class Person {
private String name;
private int age;
private Address address; // Reference type
// Regular constructor
public Person(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
// Copy constructor in Java
public Person(Person original) {
this.name = original.name;
this.age = original.age;
// Deep copy for reference type
this.address = new Address(original.address);
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address.getStreet() + ", " + address.getCity());
}
}
class Address {
private String street;
private String city;
public Address(String street, String city) {
this.street = street;
this.city = city;
}
// Copy constructor for Address
public Address(Address original) {
this.street = original.street;
this.city = original.city;
}
// Getters
public String getStreet() { return street; }
public String getCity() { return city; }
// Setters
public void setStreet(String street) { this.street = street; }
public void setCity(String city) { this.city = city; }
}
class CopyConstructorDemo {
public static void main(String[] args) {
// Create original object
Address address = new Address("123 Main St", "New York");
Person original = new Person("John", 30, address);
// Create copy using copy constructor
Person copy = new Person(original);
// Display both objects
System.out.println("Original Person:");
original.displayInfo();
System.out.println("\nCopied Person:");
copy.displayInfo();
// Modify the original address
address.setStreet("456 Park Ave");
address.setCity("Boston");
// Display both objects again to show deep copy worked
System.out.println("\nAfter modifying original address:");
System.out.println("Original Person:");
original.displayInfo();
System.out.println("\nCopied Person (unchanged due to deep copy):");
copy.displayInfo();
}
}
Output:
Original Person:
Name: John
Age: 30
Address: 123 Main St, New York
Copied Person:
Name: John
Age: 30
Address: 123 Main St, New York
After modifying original address:
Original Person:
Name: John
Age: 30
Address: 456 Park Ave, Boston
Copied Person (unchanged due to deep copy):
Name: John
Age: 30
Address: 123 Main St, New York
When to use copy constructor in Java:
Constructor overloading in Java refers to the ability to define multiple constructors within the same class with different parameter lists. This provides flexibility in object creation. Each constructor overloading in Java represents a different way to initialize an object.
public class Product {
private String name;
private double price;
private String category;
// Constructor 1
public Product() {
this.name = "Unknown";
this.price = 0.0;
this.category = "General";
}
// Constructor 2
public Product(String name) {
this.name = name;
this.price = 0.0;
this.category = "General";
}
// Constructor 3
public Product(String name, double price) {
this.name = name;
this.price = price;
this.category = "General";
}
// Constructor 4
public Product(String name, double price, String category) {
this.name = name;
this.price = price;
this.category = category;
}
public void displayInfo() {
System.out.println("Product: " + name);
System.out.println("Price: $" + price);
System.out.println("Category: " + category);
}
public static void main(String[] args) {
// Using different overloaded constructors
Product p1 = new Product();
Product p2 = new Product("Laptop");
Product p3 = new Product("Smartphone", 999.99);
Product p4 = new Product("Coffee Maker", 89.99, "Appliances");
System.out.println("Product 1 (No-arg constructor):");
p1.displayInfo();
System.out.println("\nProduct 2 (Name only):");
p2.displayInfo();
System.out.println("\nProduct 3 (Name and price):");
p3.displayInfo();
System.out.println("\nProduct 4 (All parameters):");
p4.displayInfo();
}
}
Output:
Product 1 (No-arg constructor):
Product: Unknown
Price: $0.0
Category: General
Product 2 (Name only):
Product: Laptop
Price: $0.0
Category: General
Product 3 (Name and price):
Product: Smartphone
Price: $999.99
Category: General
Product 4 (All parameters):
Product: Coffee Maker
Price: $89.99
Category: Appliances
Rules for constructor overloading in Java:
Benefits of constructor overloading in Java:
Although constructors look similar to methods, they have distinct differences. Understanding constructor vs method in Java is essential for proper object-oriented programming.
Feature | Constructor in Java | Method in Java |
Name | Must be the same as the class name | Can have any valid identifier |
Return Type | No return type, not even void | Must have a return type (void or specific type) |
Invocation | Called automatically when object is created | Called explicitly using object reference |
Purpose | To initialize objects | To perform operations or calculations |
Inheritance | Not inherited by subclasses | Methods are inherited by subclasses |
Overriding | Cannot be overridden | Can be overridden in subclasses |
Static | Cannot be declared static | Can be declared static |
Number | Multiple constructors with different parameters | Multiple methods with different signatures |
Final | Cannot be declared final | Can be declared final |
Abstract | Cannot be declared abstract | Can be declared abstract |
This comparison highlights the specialized role of constructors in object initialization compared to the general-purpose nature of methods.
The short answer is no, we cannot override a constructor in Java. Constructors are not inherited by subclasses, so the concept of overriding doesn't apply to them. However, there are related concepts that may cause confusion.
Why can we not override the constructor in Java?
While we cannot override a constructor in Java, we can:
public class Parent {
// Parent constructor
public Parent() {
System.out.println("Parent constructor");
}
}
public class Child extends Parent {
// Child constructor - NOT overriding
public Child() {
// Implicitly calls super()
System.out.println("Child constructor");
}
public static void main(String[] args) {
// Creating a Child object
Child child = new Child();
}
}
Output:
Parent constructor
Child constructor
In this example, the Child constructor is not overriding the Parent constructor. It's a new constructor that automatically calls the parent constructor via the implicit super() call.
Creating a constructor in Java is straightforward. Here's a step-by-step guide on how to create a constructor in Java:
Here's a practical example of how to create a constructor in Java:
public class Car {
// Fields
private String make;
private String model;
private int year;
private double price;
// Default constructor
public Car() {
this.make = "Unknown";
this.model = "Unknown";
this.year = 2023;
this.price = 0.0;
}
// Parameterized constructor
public Car(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
// Partial parameterized constructor
public Car(String make, String model) {
this.make = make;
this.model = model;
this.year = 2023;
this.price = 0.0;
}
// Display method
public void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Price: $" + price);
}
}
Testing the constructors:
public class CarTest {
public static void main(String[] args) {
// Using default constructor
Car car1 = new Car();
System.out.println("Car 1 Info:");
car1.displayInfo();
// Using fully parameterized constructor
Car car2 = new Car("Toyota", "Camry", 2023, 25000.0);
System.out.println("\nCar 2 Info:");
car2.displayInfo();
// Using partial parameterized constructor
Car car3 = new Car("Honda", "Civic");
System.out.println("\nCar 3 Info:");
car3.displayInfo();
}
}
Output:
Car 1 Info:
Make: Unknown
Model: Unknown
Year: 2023
Price: $0.0
Car 2 Info:
Make: Toyota
Model: Camry
Year: 2023
Price: $25000.0
Car 3 Info:
Make: Honda
Model: Civic
Year: 2023
Price: $0.0
Common mistakes when creating a constructor in Java:
Constructor chaining in Java refers to the process of calling one constructor from another constructor within the same class. This technique helps reduce code duplication and improves maintainability. Constructor chaining is implemented using the this() keyword.
public class Student {
private int id;
private String name;
private String department;
private int age;
// Constructor 1: All parameters
public Student(int id, String name, String department, int age) {
this.id = id;
this.name = name;
this.department = department;
this.age = age;
}
// Constructor 2: Calls Constructor 1
public Student(int id, String name, String department) {
this(id, name, department, 18); // Default age is 18
}
// Constructor 3: Calls Constructor 2
public Student(int id, String name) {
this(id, name, "Computer Science"); // Default department
}
// Constructor 4: Calls Constructor 3
public Student(int id) {
this(id, "Unknown"); // Default name
}
// Constructor 5: Default constructor calls Constructor 4
public Student() {
this(0); // Default id
}
public void displayDetails() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
// Creating objects using different constructors in the chain
Student s1 = new Student(101, "John Doe", "Physics", 22);
Student s2 = new Student(102, "Jane Smith", "Mathematics");
Student s3 = new Student(103, "Bob Johnson");
Student s4 = new Student(104);
Student s5 = new Student();
System.out.println("Student 1 (All parameters):");
s1.displayDetails();
System.out.println("\nStudent 2 (ID, Name, Department):");
s2.displayDetails();
System.out.println("\nStudent 3 (ID, Name):");
s3.displayDetails();
System.out.println("\nStudent 4 (ID only):");
s4.displayDetails();
System.out.println("\nStudent 5 (No parameters):");
s5.displayDetails();
}
}
Output:
Student 1 (All parameters):
ID: 101
Name: John Doe
Department: Physics
Age: 22
Student 2 (ID, Name, Department):
ID: 102
Name: Jane Smith
Department: Mathematics
Age: 18
Student 3 (ID, Name):
ID: 103
Name: Bob Johnson
Department: Computer Science
Age: 18
Student 4 (ID only):
ID: 104
Name: Unknown
Department: Computer Science
Age: 18
Student 5 (No parameters):
ID: 0
Name: Unknown
Department: Computer Science
Age: 18
In this example, we have five constructors chained together. The key points about this constructor chaining in Java are:
Constructor chaining can also occur between superclass and subclass constructors using the super() keyword. This is known as constructor chaining across classes.
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this(name, 0); // Age defaults to 0
}
public void displayInfo() {
System.out.println("Person: " + name + ", Age: " + age);
}
}
class Employee extends Person {
private String company;
public Employee(String name, int age, String company) {
super(name, age); // Calls parent constructor
this.company = company;
}
public Employee(String name, String company) {
super(name); // Calls parent constructor with name only
this.company = company;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Company: " + company);
}
public static void main(String[] args) {
Employee emp1 = new Employee("John Doe", 35, "Acme Inc.");
Employee emp2 = new Employee("Jane Smith", "Tech Corp");
System.out.println("Employee 1:");
emp1.displayInfo();
System.out.println("\nEmployee 2:");
emp2.displayInfo();
}
}
Output:
Employee 1:
Person: John Doe, Age: 35
Company: Acme Inc.
Employee 2:
Person: Jane Smith, Age: 0
Company: Tech Corp
Constructor chaining benefits:
Constructors in Java are essential components of object-oriented programming. They ensure proper object initialization during creation. Understanding the different types of constructor in Java helps write more robust and maintainable code. Default constructors provide basic initialization, while parameterized constructors offer flexibility. Constructor overloading enables multiple ways to create objects.
Copy constructors allow object duplication with the same state. Though constructors look like methods, they serve a specific purpose in object creation. By mastering constructors, you'll write more efficient Java code and create objects that are always in a valid state.
A constructor in Java is a special method that has the same name as the class. It is used to initialize objects and is called automatically when an object is created using the new keyword. Unlike regular methods, constructors don't have a return type, not even void. Constructors provide a way to set up the initial state of an object, ensuring that all objects start with valid values.
We use constructor in Java to initialize objects during creation. Constructors ensure that objects always start in a valid state. They provide a clean way to set initial values, enforce business rules, and maintain object integrity from the moment of creation. Constructors also help in implementing encapsulation by allowing controlled access to object initialization.
A default constructor in Java is a no-argument constructor that is automatically provided by the Java compiler if no constructors are explicitly defined in a class. It initializes instance variables to their default values (0, false, null). Once any constructor is defined, the compiler doesn't provide the default one. Default constructors maintain backward compatibility and ensure objects can be created without parameters.
To create a constructor in Java, define a method with the same name as the class without any return type. Choose an access modifier (usually public), define parameters if needed, and write initialization code in the body. Constructors can be overloaded with different parameter lists. Always validate input parameters and initialize all necessary fields to ensure object integrity.
No, we cannot override a constructor in Java because constructors are not inherited by subclasses. Since constructors must have the same name as the class, a subclass constructor will have a different name than its parent class constructor. However, subclass constructors can call parent constructors using the super() keyword. This distinction is fundamental to understanding Java's inheritance model.
There are three main types of constructors in Java: default constructor (no parameters), parameterized constructor (with parameters), and copy constructor (creates a copy of an existing object). Java provides an implicit default constructor only if no other constructors are defined in the class. Each type serves a specific purpose in object creation and initialization, providing flexibility in how objects are initialized.
Constructor overloading in Java is the technique of defining multiple constructors within the same class with different parameter lists. This allows objects to be initialized in different ways. Each constructor must have a unique parameter signature, differing in number, type, or order of parameters. Constructor overloading improves code flexibility and readability by providing multiple initialization options.
Yes, a constructor can be private in Java. A private constructor prevents the class from being instantiated from outside the class. This is commonly used in singleton patterns, utility classes, or when object creation should be controlled through factory methods. Private constructors provide a way to enforce design patterns that limit how objects are created.
Constructor chaining in Java refers to the process of calling one constructor from another within the same class using this(), or calling a parent class constructor using super(). It helps reduce code duplication and centralize initialization logic. The this() or super() call must be the first statement in the constructor. Constructor chaining is a powerful technique for maintaining clean, DRY (Don't Repeat Yourself) code.
If you don't define any constructors in a Java class, the compiler automatically provides a default no-argument constructor. This implicit constructor has the same access modifier as the class, initializes all instance variables to default values, and calls the superclass's no-argument constructor. This ensures that all classes can be instantiated, maintaining Java's object-oriented nature.
The main differences include: constructors must have the same name as the class while methods can have any name; constructors don't have a return type while methods must have one; constructors are called automatically during object creation while methods need explicit calls; and constructors initialize objects while methods perform operations. Understanding these differences is crucial for proper object-oriented programming.
A copy constructor in Java creates a new object as a copy of an existing object of the same class. It takes an object of the class as a parameter and creates a new object with the same field values. Java doesn't provide built-in copy constructors like C++, but they can be implemented manually to create deep copies of objects. Copy constructors are essential when you need independent copies of objects with complex internal structures. class initializes all instance variables to default values and calls the superclass's no-argument constructor.
The main differences include: constructors must have the same name as the class while methods can have any name; constructors don't have a return type while methods must have one; constructors are called automatically during object creation while methods need explicit calls; and constructors initialize objects while methods perform operations.
A copy constructor in Java creates a new object as a copy of an existing object of the same class. It takes an object of the class as a parameter and creates a new object with the same field values. Java doesn't provide built-in copy constructors like C++, but they can be implemented manually to create deep copies of objects.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
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.