Constructors
A constructor is a special block of code, similar to a method, that runs automatically when an object is created. It's typically used to set up initial values for an object's fields.
1. What is a Constructor?
A constructor is a special block of code, similar to a method, that runs automatically when an object is created. It's typically used to set up initial values for an object's fields.
2. Why is it used?
Without a constructor, you'd need to manually set every field's value right after creating each object. A constructor lets you set these initial values automatically, right at the moment of creation.
3. Real-Life Example
Think of filling out basic details (name, date) the moment you open a new notebook for the first time, before writing anything else in it. A constructor performs this same kind of initial setup automatically, the moment an object is created.
4. Syntax
javaclass ClassName { ClassName() { // constructor code, runs when object is created } }
5. Example Program
javaclass Student { String name; Student(String studentName) { name = studentName; } } public class ConstructorDemo { public static void main(String[] args) { Student s = new Student("Rohan"); System.out.println("Student name: " + s.name); } }
Output:
Student name: Rohan6. Key Points to Remember
- A constructor has the same name as the class and no return type, not even
void. - If you don't write any constructor, Java automatically provides an empty default constructor.
- A class can have multiple constructors with different parameters — this is called constructor overloading.