-
Hajipur, Bihar, 844101
In Java, constructors are special methods used to initialize objects. Whenever you create an object of a class, a constructor is automatically called to assign initial values to the object’s attributes. Constructors make sure every new object starts in a valid state.
In simple terms, a constructor prepares an object for use by setting up its data. Without constructors, you would have to manually assign values to every object right after creating it.
A constructor is a special method in Java that:
Has the same name as the class.
Does not have a return type (not even void).
Runs automatically when an object is created.
Example:
class Student {
String name;
Student() {
System.out.println("Constructor called!");
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Constructor is called automatically
}
}
Output:
Constructor called!
Here, when the object s1 is created, the constructor runs automatically.
Constructors are mainly used for:
Initializing object attributes
Reducing repetitive code
Ensuring data consistency
Without constructors, you would need to call separate setter methods every time you create a new object.
Java supports three types of constructors:
Default Constructor
Parameterized Constructor
Copy Constructor (manual, since Java doesn’t have a built-in one)
Let’s understand each in detail.
A default constructor is created automatically by Java if you don’t define any constructor yourself. It initializes all fields to their default values (like 0, null, or false).
Example:
class Student {
String name;
int age;
Student() {
name = "Unknown";
age = 18;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.display();
}
}
Output:
Name: Unknown, Age: 18
Here, the default constructor assigns default values automatically when the object is created.
A parameterized constructor takes arguments to initialize the object with specific values. This helps in setting different values for different objects.
Example:
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Anjali", 21);
Student s2 = new Student("Meera", 19);
s1.display();
s2.display();
}
}
Output:
Name: Anjali, Age: 21
Name: Meera, Age: 19
This shows how each object can have different data using parameterized constructors.
Java allows you to define multiple constructors in the same class with different parameter lists. This is called constructor overloading.
Example:
class Box {
int length, width, height;
Box() {
length = width = height = 1;
}
Box(int l, int w, int h) {
length = l;
width = w;
height = h;
}
void volume() {
System.out.println("Volume: " + (length * width * height));
}
}
public class Main {
public static void main(String[] args) {
Box b1 = new Box();
Box b2 = new Box(5, 6, 7);
b1.volume();
b2.volume();
}
}
Output:
Volume: 1
Volume: 210
Here, the same class has two constructors. The right one runs depending on how you create the object.
Java does not provide a built-in copy constructor like C++, but you can create your own to copy data from one object to another.
Example:
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
Student(Student s) {
name = s.name;
age = s.age;
}
void display() {
System.out.println(name + " - " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Ritika", 22);
Student s2 = new Student(s1); // Copy constructor
s2.display();
}
}
Output:
Ritika - 22
This helps create a duplicate object with the same data.
| Feature | Constructor | Method |
|---|---|---|
| Purpose | Initializes object | Performs a specific task |
| Name | Same as class | Any name |
| Return Type | None | Must have a return type |
| Called When | Object is created | Called explicitly |
| Automatically Invoked | Yes | No |
You can use the this keyword to refer to the current object and differentiate between instance variables and parameters with the same name.
Example:
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Here, this.name refers to the instance variable, while name refers to the constructor parameter.
You can call one constructor from another using this().
Example:
class Car {
String brand;
int speed;
Car() {
this("Unknown", 0);
}
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
void display() {
System.out.println(brand + " - " + speed + " km/h");
}
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car("Honda", 120);
c1.display();
c2.display();
}
}
Output:
Unknown - 0 km/h
Honda - 120 km/h
Using this() reduces code repetition and improves clarity.
In this tutorial, you learned:
What constructors are and why they are used.
The types of constructors in Java — default, parameterized, and copy.
How to overload constructors.
How constructors differ from methods.
The use of the this keyword and how to call one constructor from another.
Constructors form the base of object initialization in Java. They ensure that each object starts with the correct data and help in writing clean, reusable code.
1. Write a Java program that defines a class Person with a default constructor that prints “Object created successfully.” Create an object and check if the constructor runs automatically.
2. Create a class Car with attributes brand and price. Use a parameterized constructor to assign values to both attributes and display them using a method.
3. Write a Java program with a class Book that has two constructors — one default and one parameterized. The default constructor should set the title as “Unknown” and the author as “Not Assigned.” The parameterized constructor should accept title and author as arguments. Display details of both books.
4. Create a class Rectangle with two integer attributes length and width. Use a constructor to initialize them and a method area() to calculate and print the area.
5. Write a Java program that implements constructor overloading in a class Laptop with three constructors — one with no parameters, one with brand name, and one with brand and price. Display the values using a method.
6. Create a class Employee with attributes name and salary. Use a copy constructor to copy data from one object to another. Print both objects to verify the copied data.
7. Write a Java program where a class Mobile uses the this keyword in its constructor to differentiate between instance variables and parameters with the same name.
8. Create a class Student with two constructors — one that takes name and roll number, and another that also includes marks. Use this() to call one constructor from the other and display all details.
9. Define a class Circle with an attribute radius. Write a constructor that initializes radius and a method getArea() that returns the area of the circle. Create multiple objects with different radii and print their areas.
10. Write a Java program with a class Account that initializes accountNumber and balance using a constructor. Create multiple accounts with different values and display their details using a method.