Constructors in Java — Java Technical Interview Questions & Answers
Constructors in Java
Constructors in Java
- A constructor runs when you create an object. It sets starting values. Same name as the class. No return type — not even void. new Box(4) calls the constructor and creates the object.
- If you write no constructor, Java adds an empty default one. A parameterized constructor takes values at creation. You can overload: many constructors with different parameter lists.
- void Box() is a normal method, not a constructor. That is the classic trap. Contrast: constructor initialises; method does later work.
- Let's take this on the board with one tiny Main class — no extra files. Constructors in Java — output: 4. new Box(4) runs the constructor and sets side. No setter needed. Start from main, go line by line, and stop at each print. That output is the proof for Constructors.
Technical Interview Tip: Contrast constructor vs method: return type is the difference.
Code Examples for Constructors in Java
Example
class Box {
int side;
Box(int s) { side = s; }
}
public class Main {
public static void main(String[] args) {
Box b = new Box(4);
System.out.println(b.side);
}
}Constructors in Java — output: 4. new Box(4) runs the constructor and sets side. No setter needed.
How to Explain Constructors in Java to an Interviewer
When does a constructor run?
When you create an object with new
Can a constructor have a return type?
No Not even void
What is constructor overloading?
Many constructors Different parameter lists
What is void Box()?
A normal method Not a constructor