A Java constructor is a special block of code inside a class that is automatically invoked when a new instance (object) of that class is created using the new keyword. Its primary purpose is to initialize the state of the newly created object by assigning values to its instance variables.
Key Characteristics of Java Constructors
- Same Name as Class
- A constructor is called automatically when an object is created using new.
- Constructors can have parameters and can be overloaded.
Types of Constructors
1.Default (No-Argument) Constructor
If you do not define any constructor in your class, the Java compiler automatically generates a hidden, no-argument default constructor for you. It initializes object references to null and numeric primitive types to 0.
public class Car {
String brand;
int speed;
// The compiler automatically creates this behind the scenes:
// public Car() {}
}
// Usage
Car myCar = new Car(); // brand will be null, speed will be 0
2.Parameterized Constructor
You can write a custom constructor that accepts arguments. This provides the flexibility to assign specific, custom values to your object's attributes at the moment it is created.
public class Car {
String brand;
int speed;
// Parameterized constructor
public Car(String brand, int speed) {
this.brand = brand; // "this" resolves naming conflicts between parameters and fields
this.speed = speed;
}
}
// Usage
Car myCar = new Car("Toyota", 120);
3.Copy Constructor
Unlike C++, Java does not have a built-in copy constructor. However, you can easily create your own by writing a constructor that takes an object of the same class as a parameter to copy its values.
public Car(Car otherCar) {
this.brand = otherCar.brand;
this.speed = otherCar.speed;
}
Constructor Overloading
Just like methods, constructors can be overloaded. This means a single class can have multiple constructors, provided they have different parameter lists (different number, order, or types of parameters). The compiler automatically decides which constructor to execute based on the arguments passed.
public class Car {
String brand;
int speed;
// Constructor 1: No arguments
public Car() {
this.brand = "Unknown";
this.speed = 0;
}
// Constructor 2: One argument
public Car(String brand) {
this.brand = brand;
this.speed = 0;
}
// Constructor 3: Two arguments
public Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
}
Top comments (0)