A constructor is a special block of code that we can use to initialize objects of a class. Think of it as a setup method that prepares an object with default or initial values when it is created.
A constructor has no return type, and its name must exactly match the class name. Java automatically calls the constructor when you create an object using the new keyword.
Features of a Constructor in Java
1) name matches the Class: The constructor must have the same name as the class. So Java identifies it as a constructor.
Example:
class Car {
Car() { // Constructor name same as class
System.out.println("Car object created!");
}
}
2) No Return Type: Unlike regular methods, constructors do not return any value, and you do not specify a return type, not even void.
Example:
class Car {
Car() { // Correct constructor
System.out.println("Constructor called");
}
}
3) Automatically Invoked: Constructors are called automatically when an object is created with the new keyword. You don’t need to call it explicitly. For example:
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Constructor automatically called
}
}
Output:
Car object created!
Syntax of a Constructor
This is the basic syntax of a constructor:
class ClassName {
// Constructor
ClassName() {
// Constructor body
// Code to initialize the object
}
}
Types of Constructors in Java
Constructors can be classified into three main types based on how they initialize objects:
- Default Constructor
- Parameterized Constructor
- Copy Constructor
1. Default Constructor
A default constructor is a constructor with no arguments, and if you don’t explicitly define any constructor in a class, Java provides a default constructor automatically.
Example: Default Constructor
class Student {
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 0;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Calls default constructor
s1.display();
}
}
Output:
Name: Unknown, Age: 0
Explanation of this code:
- The constructor initializes name to “Unknown” and age to 0.
- No values are required when creating the object.
2. Parameterized Constructor
A parameterized constructor accepts arguments to initialize object attributes with custom values. It allows you to create objects with specific values at the time of creation.
Example: Parameterized Constructor
class Student {
String name;
int age;
// Parameterized constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20); // Pass values to constructor
s1.display();
}
}
Output:
Name: Alice, Age: 20
- In this code, the constructor takes name and age as parameters and sets the object’s attributes accordingly.
3. Copy Constructor
A copy constructor creates a new object as a copy of an existing object. But Java does not provide a built-in copy constructor, but you can create one manually.
It’s useful when you want to duplicate objects with the same attribute values.
Example: Copy Constructor
class Student {
String name;
int age;
// Parameterized constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
Student(Student other) {
this.name = other.name;
this.age = other.age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("John", 22); // Original object
Student s2 = new Student(s1); // Copy object
s2.display();
}
}
Output:
Name: John, Age: 22
- In this code, s2 is a new object created as a copy of s1.
- Both objects have the same attribute values, but they are separate objects in memory.
What Is Constructor Overloading In Java?
Constructor overloading allows a class to have more than one constructor, each with a different parameter list.
This feature gives you the flexibility to create objects in multiple ways, depending on the information available at the time of object creation.
Example: Constructor Overloading
class Employee {
String name;
int salary;
// Default constructor (no arguments)
Employee() {
name = "Not Assigned";
salary = 0;
}
// Parameterized constructor (two arguments)
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
// Another parameterized constructor (only name)
Employee(String name) {
this.name = name;
salary = 10000; // default salary
}
void display() {
System.out.println("Name: " + name + ", Salary: " + salary);
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee(); // Calls default constructor
Employee emp2 = new Employee("John", 50000); // Calls parameterized constructor with 2 arguments
Employee emp3 = new Employee("Alice"); // Calls parameterized constructor with 1 argument
emp1.display();
emp2.display();
emp3.display();
}
}
Output:
Name: Not Assigned, Salary: 0
Name: John, Salary: 50000
Name: Alice, Salary: 10000
Learn this code carefully:
- emp1 is a default constructor because it has no arguments provided.
- emp2 is the constructor with two parameters is called to set both name and salary.
- emp3 is defined with one parameter, and salary is set to a default value.
Special Keywords in Constructors
Java provides two most important keywords are this and super.
1) this Keyword: The this keyword refers to the current object of the class. Its main purpose is to distinguish between instance variables and parameters when they have the same name.
For example:
class Book {
String title;
double price;
// Constructor
Book(String title, double price) {
this.title = title; // 'this.title' refers to the instance variable
this.price = price; // 'price' is the parameter
}
void showDetails() {
System.out.println("Book Title: " + title + ", Price: $" + price);
}
}
public class Main {
public static void main(String[] args) {
Book b1 = new Book("Java Essentials", 450.75);
Book b2 = new Book("Data Structures", 320.50);
b1.showDetails();
b2.showDetails();
}
}
Output:
Book Title: Java Essentials, Price: $450.75
Book Title: Data Structures, Price: $320.5
Explanation of this code:
- The constructor parameters title and price have the same names as the instance variables.
- Using this.title and this.price ensures that the object’s instance variables are assigned, not the parameters themselves.
- Each Book object can now have its own unique title and price.
2) super Keyword: The super keyword is used to call the constructor of the parent class in inheritance.
Its main purpose is to initialize the parent class before the child class, thereby reusing code and ensuring proper object construction in inheritance hierarchies.
Example:
class Vehicle {
String brand;
Vehicle(String brand) {
this.brand = brand; // Initialize parent class attribute
}
}
class Car extends Vehicle {
int speed;
Car(String brand, int speed) {
super(brand); // Call parent class constructor
this.speed = speed; // Initialize child class attribute
}
void showDetails() {
System.out.println("Brand: " + brand + ", Max Speed: " + speed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Tesla", 250);
Car anotherCar = new Car("BMW", 220);
myCar.showDetails();
anotherCar.showDetails();
}
}
Output:
Brand: Tesla, Max Speed: 250 km/h
Brand: BMW, Max Speed: 220 km/h
Explanation:
- The Car class extends the Vehicle class.
- super(brand) calls the constructor of the parent class Vehicle to initialize the brand attribute.
Exercise: Library Book Management
Create a simple Library Book Management System in Java. Each Book has the following attributes:
- title (String)
- author (String)
- price (double)
And the library also has a SpecialBook class that inherits from Book and adds:
- category (String)
- discount (double)
Your tasks:
- Create a Book class:
- Default constructor should set title = “Unknown”, author = “Unknown”, price = 0.0.
- Parameterized constructor should initialize all attributes.
- The copy constructor should create a new object as a copy of an existing Book.
- Add a method displayBook() to print the book details.
- Create a SpecialBook class that extends Book:
- Add category and discount attributes.
- Parameterized constructor should use super to initialize title, author, and price.
- Add a method displaySpecialBook() to print all details, including category and discounted price.
- In the main method:
- Create 1 book using the default constructor.
- Create 1 book using parameterized constructor.
- Create 1 book using the copy constructor.
- Create a special book and display all details, including the discounted price.
Try this exercise by yourself to master the constructor concept in Java.