A constructor initializes new objects. It shares the class name, has no return type, and runs when new is called. If you omit one, Java provides a default no-arg constructor until you define any constructor.
Example
class Product {
final String sku;
final double price;
Product(String sku, double price) {
this.sku = sku;
this.price = price;
}
}
this refers to the current instance—disambiguates parameters from fields.
Constructor chaining
Product(String sku) {
this(sku, 0.0);
}
Important interview questions and answers
- Q: Constructor vs method?
A: Same name as class, no return type, invoked only vianew. - Q: What happens when you add a parameterized constructor?
A: Default no-arg constructor is not generated—you must define it explicitly if needed.
Self-check
- What keyword calls another constructor in the same class?
- Why use
finalfields set in the constructor?