05.Types of Constructors in Java
Great! Let’s dive into Types of Constructors in Java with clear explanations and examples.
Constructors in Java
Definition: Special method used to initialize objects of a class.
Key Points:
Name same as the class.
No return type (not even void).
Called automatically when object is created.
1. Default Constructor
Definition: Constructor with no parameters.
Types:
Compiler-provided default constructor: Automatically added if no constructor is defined.
User-defined default constructor: Explicitly written by the programmer.
Example (User-defined default constructor):
class Car {
Car() { // Default constructor
System.out.println("Car object created");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car(); // Calls default constructor
}
}
2. Parameterized Constructor
- Definition: Constructor with parameters to initialize object with specific values.
Example:
class Car {
String brand;
int speed;
Car(String brand, int speed) { // Parameterized constructor
this.brand = brand;
this.speed = speed;
}
void display() {
System.out.println(brand + " " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car("BMW", 200);
c1.display(); // BMW 200
}
}
3. Copy Constructor (Manual in Java)
Definition: Constructor that creates a new object as a copy of an existing object.
Note: Java does not provide automatic copy constructors like C++, so we write manually.
Example:
class Car {
String brand;
int speed;
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
// Copy constructor
Car(Car c) {
this.brand = c.brand;
this.speed = c.speed;
}
void display() {
System.out.println(brand + " " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car("Audi", 220);
Car c2 = new Car(c1); // Copy constructor
c2.display(); // Audi 220
}
}
4. Private Constructor
Definition: Constructor declared
private; used to restrict object creation outside the class.Use Case: Singleton pattern or utility classes.
Example (Singleton):
class Singleton {
private static Singleton instance;
private Singleton() {} // Private constructor
public static Singleton getInstance() {
if(instance == null) instance = new Singleton();
return instance;
}
}
public class Main {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // true
}
}
✅ Summary Table – Types of Constructors
| Constructor Type | Parameters | Object Creation | Example Use Case |
| Default | None | Object initialized with default values | Simple object creation |
| Parameterized | Yes | Initialize with specific values | Set object properties at creation |
| Copy | Object | Create new object from existing object | Duplicate objects |
| Private | None / Parameterized | Restrict instantiation | Singleton, Utility classes |
Comments
Join the discussionNo comments yet. Be the first to comment.