Constructors

Thinking

Constructors are special methods used to initialize objects when they are created.

Understanding how default and parameterized constructors work helps in setting up object state properly at the time of creation.

Description

A constructor is a special method in a class that is called automatically when an object is instantiated.

Key points about constructors:

  • The constructor name must match the class name.
  • Constructors do not have a return type, not even void.
  • Default Constructor: Provided by Java if no constructor is defined; it initializes objects with default values.
  • Parameterized Constructor: Allows passing arguments to initialize objects with specific values.
  • Constructors can be overloaded by defining multiple constructors with different parameters.

Video Resources

Java Constructors

Comprehensive tutorial on constructors and their use in Java.

Examples (code)

Default Constructor Example


class Person {
    String name;
    int age;

    // Default constructor
    Person() {
        name = "Unknown";
        age = 0;
    }

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

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person();
        p1.display();
    }
}
  

Parameterized Constructor Example


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: " + name + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Person p2 = new Person("Alice", 25);
        p2.display();
    }
}
  

Real-World Applications

User Account Creation

Constructors initialize user profiles with default or provided details.

E-commerce Orders

Order objects are created with parameterized constructors to hold order info.

Robotics Control

Robots initialized with different parameters using constructors for flexibility.

Interview Questions

Q1: What is a constructor in Java?

Show Answer

A constructor is a special method used to initialize objects when they are created. It has the same name as the class and no return type.

Q2: What is the difference between default and parameterized constructors?

Show Answer

The default constructor has no parameters and initializes default values, while parameterized constructors accept arguments to initialize the object with specific values.

Q3: Can constructors be overloaded in Java?

Show Answer

Yes, constructors can be overloaded by defining multiple constructors with different parameter lists.