What is a Constructor in Java?
A constructor in Java is a special method that is automatically called when an object is created.
It is used to initialize objects.
Key Features of Constructors
- Same name as the class
- No return type (not even
void)
- Called automatically during object creation
- Can be overloaded (i.e., multiple constructors with different parameters)
Types of Constructors
- Default Constructor (no parameters)
- Parameterized Constructor (with parameters)
- Constructor Overloading (multiple constructors)
Example 1: Default Constructor
class Car {
// Default constructor
Car() {
System.out.println("Car object is created!");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Constructor is automatically called
}
}
Output:
Car object is created!
Example 2: Parameterized Constructor
class Student {
String name;
int age;
// Parameterized constructor
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("Alice", 20);
s1.display();
}
}
Output:
Name: Alice, Age: 20
Example 3: Constructor Overloading
class Book {
String title;
int pages;
// Constructor 1 - default
Book() {
title = "Unknown";
pages = 0;
}
// Constructor 2 - parameterized
Book(String t, int p) {
title = t;
pages = p;
}
void showDetails() {
System.out.println("Title: " + title + ", Pages: " + pages);
}
}
public class Main {
public static void main(String[] args) {
Book b1 = new Book();
Book b2 = new Book("Java Basics", 250);
b1.showDetails();
b2.showDetails();
}
}
Output:
Title: Unknown, Pages: 0
Title: Java Basics, Pages: 250
Why Use Constructors?
- To initialize object fields when an object is created.
- To provide default or custom values.
- To keep code cleaner and more consistent.
Difference: Constructor vs Method
| Feature |
Constructor |
Method |
| Name |
Same as class name |
Any name |
| Return type |
No return type |
Must have return type |
| Called |
Automatically during object creation |
Manually (by object reference) |
| Purpose |
Initializes an object |
Defines behavior |