Java - Constructors and Methods-interview
Q1. What is the difference between a constructor and a method in Java?
- Constructor: Used to initialize objects, has no return type, name must match the class name, called automatically when an object is created.
- Method: Used to define behavior, must have a return type (or void), can have any name, called explicitly.
Q2. Can a constructor be static or final in Java?
No. Constructors cannot be static (not tied to class) or final (not inherited/overridden).
Q3. What are the types of constructors in Java?
- Default Constructor – No parameters, provided by compiler if not defined.
- Parameterized Constructor – Takes arguments to initialize object with specific values.
- Copy Constructor (custom) – Used to create a copy of another object.
Q4. Can we overload constructors and methods in Java?
Yes. Both can be overloaded by defining multiple constructors/methods with the same name but different parameter lists.
Q5. Can a constructor call another constructor in the same class?
Yes, using the this() keyword. This is called constructor chaining.