What is Java Constructor?
A Java constructor is a special method used to initialize objects when they are created. It is called automatically when an object of a class is instantiated. Constructors have the same name as the class and do not have a return type, not even void.
Key Characteristics of Constructors: #
1. Name: A constructor must have the same name as the class in which it is defined.
2. No Return Type: Constructors do not have a return type, not even void.
3. Automatic Invocation: Constructors are automatically called when an object is created.
4. Overloading: Java allows constructor overloading, meaning a class can have more than one constructor with different parameter lists.
Types of Constructors: #
- Default Constructor:
- Definition: A default constructor is a no-argument constructor provided by Java if no other constructors are defined. It initializes object fields with default values.
Example:
class Person {
String name;
int age;
// Default constructor
Person() {
name = "Unknown";
age = 0;
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
System.out.println("Name: " + p.name);
System.out.println("Age: " + p.age);
}
}
Output:
Name: Unknown
Age: 0
- Parameterized Constructor:
- Definition: A parameterized constructor allows initializing object fields with specific values provided during object creation.
Example:
class Person {
String name;
int age;
// Parameterized constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Alice", 30);
System.out.println("Name: " + p.name);
System.out.println("Age: " + p.age);
}
}
Output:
Name: Alice
Age: 30
Constructor Overloading:
Java allows multiple constructors in a class, each with different parameter lists. This is known as constructor overloading.
Example:
class Person {
String name;
int age;
// Default constructor
Person() {
name = "Unknown";
age = 0;
}
// Parameterized constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
// Another parameterized constructor with different parameters
Person(String name) {
this.name = name;
this.age = 0;
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person("Bob", 25);
Person p3 = new Person("Charlie");
System.out.println("p1 Name: " + p1.name + ", Age: " + p1.age);
System.out.println("p2 Name: " + p2.name + ", Age: " + p2.age);
System.out.println("p3 Name: " + p3.name + ", Age: " + p3.age);
}
}
Output:
p1 Name: Unknown, Age: 0
p2 Name: Bob, Age: 25
p3 Name: Charlie, Age: 0
Summary
Constructors are essential for initializing new objects in Java. They can be default or parameterized, and Java supports constructor overloading, allowing multiple constructors with different parameters to be defined in a single class.