What is a Constructor?
In Java, a constructor is a special block of code similar to a method. It is called when an instance of the class is created. The primary purpose of a constructor is to initialize the newly created object.
When a constructor is invoked, memory for the object is allocated in the memory. Every time an object is created using the new()
keyword, at least one constructor is called. Java provides a default constructor if no constructor is explicitly defined in the class.
Characteristics of a Constructor
- Initialization: A constructor initializes the object.
- Invocation: Called automatically when a new object is created.
- Default Constructor: If no constructor is defined, Java provides a default constructor.
Rules for Creating a Java Constructor
- Constructor Name: Must be the same as the class name.
- Return Type: Must not have an explicit return type.
- Modifiers: Cannot be abstract, static, final, or synchronized.
Note: Access modifiers can be used to control object creation, allowing for private, protected, public, or default constructors in Java.
Example: Basic Constructor
public class Constructor {
String name;
int age;
Constructor(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println(name + "\n" + age);
}
public static void main(String[] args) {
Constructor p1 = new Constructor("Lalit", 20);
p1.displayInfo();
}
}
In the example above, the Constructor
class has a constructor that initializes the name
and age
fields. When a new object p1
is created using new Constructor("Lalit", 20);
, the constructor initializes the fields, and the displayInfo
method prints them.
Overloading Constructors
Constructor overloading allows a class to have more than one constructor with different parameter lists. It provides multiple ways to initialize objects.
Example: Overloaded Constructors
public class Constructor {
String name;
int age;
// Default constructor
Constructor() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized constructor
Constructor(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println(name + "\n" + age);
}
public static void main(String[] args) {
Constructor p1 = new Constructor();
Constructor p2 = new Constructor("Lalit", 20);
p1.displayInfo();
p2.displayInfo();
}
}
In this example, there are two constructors:
- Default Constructor: Initializes
name
to "Unknown" andage
to 0. - Parameterized Constructor: Initializes
name
andage
with the provided values.
Both objects p1
and p2
are created using different constructors, demonstrating constructor overloading.
Comments
Post a Comment