Java.Core.Define the concept of a “constructor.”

1. Key Characteristics of a Constructor

Same name as the class
No return type (not even void)
Called automatically when an object is instantiated
Used to initialize instance variables
Can be overloaded (multiple constructors in the same class)


2. Example: Basic Constructor

class Car {
    String model;

    // Constructor (same name as class)
    Car(String modelName) {
        model = modelName; // Initializing instance variable
    }

    void display() {
        System.out.println("Car Model: " + model);
    }
}

public class ConstructorExample {
    public static void main(String[] args) {
        Car car1 = new Car("Tesla Model 3"); // Constructor is called
        car1.display(); // Output: Car Model: Tesla Model 3
    }
}

The constructor initializes model when Car is created.


3. Types of Constructors

(a) Default Constructor

  • A constructor without parameters.
  • If no constructor is explicitly defined, Java automatically provides a default constructor.

Example: Default Constructor

class Animal {
    Animal() { // No parameters
        System.out.println("An Animal is Created!");
    }
}

public class DefaultConstructorExample {
    public static void main(String[] args) {
        Animal a = new Animal(); // Calls the default constructor
    }
}

Output:

An Animal is Created!

(b) Parameterized Constructor

  • Accepts arguments to initialize fields.

Example: Parameterized Constructor

class Person {
    String name;
    int age;

    // Parameterized constructor
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void display() {
        System.out.println(name + " is " + age + " years old.");
    }
}

public class ParameterizedConstructorExample {
    public static void main(String[] args) {
        Person p = new Person("Alice", 25);
        p.display(); // Output: Alice is 25 years old.
    }
}

Uses constructor parameters to initialize name and age.


(c) Copy Constructor

  • Creates a new object by copying the values of an existing object.

Example: Copy Constructor

class Book {
    String title;

    // Constructor
    Book(String title) {
        this.title = title;
    }

    // Copy Constructor
    Book(Book other) {
        this.title = other.title;
    }

    void display() {
        System.out.println("Book Title: " + title);
    }
}

public class CopyConstructorExample {
    public static void main(String[] args) {
        Book b1 = new Book("Java Programming");
        Book b2 = new Book(b1); // Copy constructor

        b1.display(); // Java Programming
        b2.display(); // Java Programming
    }
}

Creates an exact copy of b1 in b2.


(d) Private Constructor

  • Used to restrict object creation (commonly used in the Singleton pattern).

Example: Singleton Pattern Using a Private Constructor

class Singleton {
    private static Singleton instance;

    private Singleton() { // Private constructor
        System.out.println("Singleton Instance Created");
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

public class PrivateConstructorExample {
    public static void main(String[] args) {
        Singleton obj1 = Singleton.getInstance(); // Only one instance
        Singleton obj2 = Singleton.getInstance(); // Same instance reused
    }
}

Output:

Singleton Instance Created

🛑 Prevents multiple object creation!


4. Constructor Overloading

  • Multiple constructors in the same class, but with different parameters.

Example: Constructor Overloading

class Employee {
    String name;
    int age;

    // Constructor 1
    Employee() {
        this.name = "Unknown";
        this.age = 0;
    }

    // Constructor 2
    Employee(String name) {
        this.name = name;
        this.age = 0;
    }

    // Constructor 3
    Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void display() {
        System.out.println("Employee: " + name + ", Age: " + age);
    }
}

public class ConstructorOverloadingExample {
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee("Bob");
        Employee e3 = new Employee("Alice", 30);

        e1.display(); // Employee: Unknown, Age: 0
        e2.display(); // Employee: Bob, Age: 0
        e3.display(); // Employee: Alice, Age: 30
    }
}

Different constructors allow flexible object creation.


5. Difference Between Constructor and Method

FeatureConstructorMethod
PurposeInitializes an objectDefines behavior of an object
NameSame as the class nameCan have any name
Return Type❌ No return type✅ Has a return type
Called When?Automatically at object creationExplicitly called
Overloading✅ Yes, multiple constructors can exist✅ Yes, multiple methods can exist

Example: Constructor vs. Method

class Student {
    String name;

    // Constructor
    Student(String name) {
        this.name = name;
    }

    // Method
    void display() {
        System.out.println("Student Name: " + name);
    }
}

public class ConstructorVsMethodExample {
    public static void main(String[] args) {
        Student s = new Student("Alice"); // Constructor called
        s.display(); // Method called
    }
}

Constructor initializes, method displays.


6. Summary

Constructor TypeDescription
Default ConstructorNo parameters, auto-created if not defined.
Parameterized ConstructorAccepts arguments to initialize fields.
Copy ConstructorCreates a new object by copying another object.
Private ConstructorRestricts object creation (Singleton pattern).
Constructor OverloadingMultiple constructors with different parameters.

7. Conclusion

A constructor is a special method used to initialize objects in Java.
It runs automatically when an object is created.
It can be overloaded and customized for different initialization scenarios.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.