Constructors in Java
1. What is a Constructor?
A constructor is a special member of a Java class that is used to initialize objects.
Important characteristics
- Constructor name must be the same as the class name.
- A constructor does not have a return type, not even
void. - It is automatically called when an object is created using
new. - Constructors are mainly used to initialize instance variables.
- A class can have more than one constructor.
Example
class Student {
int rollNo;
String name;
Student() {
rollNo = 101;
name = "Ravi";
}
void display() {
System.out.println(rollNo);
System.out.println(name);
}
public static void main(String[] args) {
Student s1 = new Student();
s1.display();
}
}
Output
When this statement executes:
the constructor Student() is automatically called.
2. Default Constructor
If you do not write any constructor in a class, Java provides a default constructor automatically.
Java conceptually provides:
Therefore:
is valid.
The instance variables receive their default values:
Important point
If you write any constructor yourself, Java does not automatically provide the no-argument default constructor.
For example:
This is valid:
But this is invalid:
because no Student() constructor has been defined.
3. No-Argument Constructor
A constructor that does not accept any parameters is called a no-argument constructor.
class Employee {
int empNo;
String name;
Employee() {
empNo = 101;
name = "Anil";
}
}
Creating the object:
calls:
4. Parameterized Constructor
A constructor that accepts parameters is called a parameterized constructor.
class Student {
int rollNo;
String name;
Student(int r, String n) {
rollNo = r;
name = n;
}
void display() {
System.out.println(rollNo + " " + name);
}
public static void main(String[] args) {
Student s1 = new Student(101, "Ravi");
Student s2 = new Student(102, "Sita");
s1.display();
s2.display();
}
}
Here:
passes 101 and "Ravi" to the constructor.
5. Constructor Overloading
Constructor overloading means defining multiple constructors in the same class with different parameter lists.
The constructors must differ in:
- Number of parameters, or
- Type of parameters, or
- Order of parameters
Example
class Student {
int rollNo;
String name;
double marks;
Student() {
rollNo = 0;
name = "Unknown";
marks = 0;
}
Student(int r) {
rollNo = r;
name = "Unknown";
marks = 0;
}
Student(int r, String n) {
rollNo = r;
name = n;
marks = 0;
}
Student(int r, String n, double m) {
rollNo = r;
name = n;
marks = m;
}
void display() {
System.out.println(rollNo + " " + name + " " + marks);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student(101);
Student s3 = new Student(102, "Ravi");
Student s4 = new Student(103, "Sita", 85.5);
s1.display();
s2.display();
s3.display();
s4.display();
}
}
Here the class contains four overloaded constructors.
Java determines which constructor to call based on the arguments supplied with new.
6. Constructor Overloading Based on Data Type
Constructors can also be overloaded using different parameter types.
class Demo {
Demo(int x) {
System.out.println("Integer constructor");
}
Demo(double x) {
System.out.println("Double constructor");
}
Demo(String x) {
System.out.println("String constructor");
}
public static void main(String[] args) {
Demo d1 = new Demo(10);
Demo d2 = new Demo(10.5);
Demo d3 = new Demo("Java");
}
}
Output:
7. Constructor Overloading Based on Order of Parameters
Parameter order can also be different.
class Person {
Person(int age, String name) {
System.out.println("Age: " + age + ", Name: " + name);
}
Person(String name, int age) {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Person p1 = new Person(25, "Ravi");
Person p2 = new Person("Sita", 22);
}
}
The parameter lists are different:
Therefore, these are valid overloaded constructors.
8. Constructor vs Method
| Constructor | Method |
|---|---|
| Same name as class | Can have any valid name |
| No return type | May have a return type |
| Automatically called when object is created | Usually called explicitly |
| Used mainly for initialization | Used to perform operations |
| Cannot be inherited | Methods can be inherited |
| Can be overloaded | Can be overloaded |
Cannot be declared static | Can be static |
Example
class Student {
Student() { // Constructor
System.out.println("Constructor called");
}
void display() { // Method
System.out.println("Method called");
}
public static void main(String[] args) {
Student s = new Student();
s.display();
}
}
9. Using this in a Constructor
When constructor parameters have the same names as instance variables, use this.
Here:
refers to the object’s instance variable, while:
refers to the constructor parameter.
10. Constructor Chaining Using this()
One constructor can call another constructor of the same class using this().
Execution:
Important rule
this() must be the first statement inside a constructor.
11. Calling Parent Constructor Using super()
A constructor of a child class can call the parent class constructor using super().
Output:
super() must also be the first statement of the constructor.
12. Important Rules for Constructors
Remember these points:
- Constructor name = class name.
- Constructor has no return type.
- Constructors are called when objects are created.
- Constructors can be overloaded.
- Constructor overloading is a form of compile-time polymorphism.
- Constructors cannot be inherited.
- Constructors cannot be overridden.
- A constructor can be
public,protected, default/package-private, orprivate. - A constructor cannot be
static. - A constructor cannot be
abstract. this()calls another constructor in the same class.super()calls a constructor of the parent class.this()orsuper()must be the first statement.
Practice Questions
A. Conceptual Questions
- What is a constructor in Java?
- Why does a constructor not have a return type?
- What is the difference between a constructor and a method?
- What happens if a class does not contain any constructor?
- What is a no-argument constructor?
- What is a parameterized constructor?
- What is constructor overloading?
- How does Java identify which overloaded constructor should be executed?
- Can constructors be overloaded?
- Can constructors be overridden?
- Can a constructor be declared
static? - What is the purpose of
this()inside a constructor? - What is the purpose of
super()inside a constructor? - Why must
this()be the first statement in a constructor? - What happens when a programmer defines a parameterized constructor but tries to create an object using
new ClassName()?
B. Predict the Output
Question 1
What is the output?
Question 2
Predict the output.
Question 3
What is the output and why?
C. Find the Error
Question 4
Identify the error:
Is Student() a constructor or a method?
Question 5
What is wrong with this code?
D. Programming Exercises
Beginner
- Create a
Studentclass with a no-argument constructor that initializes:rollNo = 0name = "Unknown"marks = 0
- Create an
Employeeclass with a parameterized constructor accepting employee number and employee name. - Create a
Rectangleclass with a constructor that accepts length and breadth and a method to calculate area. - Create a
BankAccountclass with a constructor that accepts account number, holder name, and balance.
Intermediate
- Create a
Studentclass with the following overloaded constructors:
Display the details of objects created using each constructor.
- Create a
Boxclass with overloaded constructors:
Calculate and display the volume.
- Create an
Employeeclass with overloaded constructors:
Display employee details.
- Create a
Productclass with overloaded constructors to initialize:- Product name only
- Product name and price
- Product name, price and quantity
Calculate the total value.
Advanced
- Create a
Studentclass using constructor chaining withthis()so that all constructors ultimately call:
- Create a
Personparent class andStudentchild class. Usesuper()to call the parent constructor and demonstrate the order in which constructors execute. - Create an
Accountclass with multiple constructors and usethis()to avoid duplicate initialization code. - Create a
Timeclass with overloaded constructors:
Display the time in HH:MM:SS format.
- Create a
Mobileclass with overloaded constructors for:
- Brand only
- Brand + model
- Brand + model + price
- Brand + model + price + storage
- Create a
Bookclass with overloaded constructors and usethis()for constructor chaining. Include suitable validation for price and quantity. - Create a
Studentclass with overloaded constructors and demonstrate the difference between constructor overloading and method overloading in the same program.