Interview on Constructors in Java : Key Questions and Answers
Interviewer : Welcome! Let’s start with the basics. Can you explain what a constructor is in Java ?
Candidate : Absolutely. A constructor in Java is a special method used to initialize objects. It has the same name as the class and does not have a return type, not even void
. Constructors are called automatically when an instance of a class is created, and they are typically used to set initial values for object attributes or to perform any setup steps needed when an object is created.
class MyClass {
int value;
// Constructor
MyClass() {
value = 10;
}
}
Interviewer : Great! Can you differentiate between a default constructor and a parameterized constructor?
Candidate: Sure. A default constructor is a no-argument constructor that is automatically provided by the Java compiler if no other constructors are defined in a class. This constructor does nothing beyond object creation.
On the other hand, a parameterized constructor takes arguments and allows you to initialize an object with specific values. If a class defines any constructors, the default constructor is not provided by the compiler.
class MyClass {
int value;
// Default constructor
MyClass() {
value = 10;
}
// Parameterized constructor
MyClass(int val) {
value = val;
}
}