What is a constructor?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid OOP Concepts basics — a prerequisite for any developer role.

Answer

A constructor is a special method that is automatically called when an object is created. It initializes the object's state (attributes) with valid initial values. Characteristics: has the same name as the class; no return type (not even void); automatically called with new; can have parameters; can be overloaded. Types of constructors: (1) Default constructor: no parameters — provided by the compiler if no constructor is defined: class Point { int x, y; public Point() { this.x = 0; this.y = 0; } // Explicit default }; (2) Parameterized constructor: public Point(int x, int y) { this.x = x; this.y = y; }; (3) Copy constructor: initializes from another instance: public Point(Point other) { this.x = other.x; this.y = other.y; }; (4) Delegating constructor (this()): one constructor calls another: public Point() { this(0, 0); } // Calls parameterized constructor; (5) Static factory methods (alternative): public static Point origin() { return new Point(0, 0); } public static Point fromCoordinates(int x, int y) { return new Point(x, y); }. Constructor vs method: constructor creates and initializes; method operates on existing objects. Inheritance and constructors: child class constructor MUST call parent constructor (explicitly via super() or implicitly via default parent constructor). Constructors are NOT inherited but can be chained. Destructor/finalizer: some languages have destructors (C++ ~ destructor, Java finalize()) called on destruction. In Java, prefer try-with-resources over finalize.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a OOP Concepts codebase.