Constructors, overloading, chaining, and common constructor pitfalls.
Question 1: What is a constructor in Java?
Ans
A constructor is a special block of code that runs automatically whenever an object is created with new, used to put the new object into a valid initial state. It has the same name as the class, has no return type at all (not even void), and can't be called directly like a normal method.
Example
java
class Student {
String name;
Student(String name) { this.name = name; }
}
Student s = new Student("Amit");
Important Point
A constructor is not inherited by subclasses, and it isn't a regular method even though its syntax looks similar.
Question 2: What is a default constructor, and when does Java provide one automatically?
Ans
If a class declares no constructor of its own, the compiler automatically inserts a no-argument "default constructor" that does nothing but call the parent's no-arg constructor. As soon as you write even one constructor yourself, Java stops adding the default one, so new MyClass() will only work if you've written a matching no-arg constructor yourself.
Example
java
class Student { } // compiler-provided no-arg constructor
Student s = new Student(); // works
Important Point
This is a common source of compile errors when someone adds a parameterized constructor and forgets the implicit no-arg one has now disappeared.
Question 3: What is constructor chaining, and how do this() and super() achieve it?
Ans
Constructor chaining means one constructor calls another constructor instead of duplicating initialization logic — this(...) calls another constructor in the same class, while super(...) calls a constructor in the parent class. Both must be the very first statement in a constructor, and only one of the two can be used in the same constructor.
Example
java
class User {
User() { this("Guest"); } // chains to the other constructor
User(String name) { /* ... */ }
}
Important Point
If you don't explicitly call this() or super(), Java silently inserts a call to the parent's no-arg constructor as the first line.
Question 4: Can constructors be inherited or overridden?
Ans
No to both. Constructors are tied specifically to building an instance of the exact class they're declared in, so they are never inherited the way normal methods are, and since they aren't inherited, "overriding" doesn't apply to them either. A subclass always defines its own constructors, which may call a parent constructor via super().
Important Point
Constructors can be overloaded (multiple constructors, different parameters) even though they can't be overridden.