Sobes.tech
Junior

What is the difference between the default constructor, copy constructor, and parameterized constructor?

sobes.tech AI

Answer from AI

  • Default constructor: Created automatically by the compiler if there are no other constructors in the class. It takes no parameters and initializes fields with default values (0 for numeric types, false for boolean, null for objects).

  • Copy constructor: Creates a new object that is a copy of an existing object of the same class. It takes one argument — a reference to the object to be copied.

  • Constructor with parameters: Allows initializing the object's fields at the time of creation by passing values as arguments. It can have any number of parameters of different types.

// Example: class Car
class Car {
    private String brand;
    private int year;

    // Default constructor (implicit, but can be explicitly declared)
    public Car() {
        // Default initialization
        this.brand = null;
        this.year = 0;
    }

    // Constructor with parameters
    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    // Copy constructor
    public Car(Car otherCar) {
        this.brand = otherCar.brand;
        this.year = otherCar.year;
    }

    // Getters, setters, and other methods
    public String getBrand() {
        return brand;
    }

    public int getYear() {
        return year;
    }
}
What is the difference between the default… - sobes.tech