Constructor
Constructor एक special method है जिसका नाम class के नाम जैसा होता है, और वो तब call होता है जब "new" keyword से object बनाया जाता है।
इससे हम object को तुरंत valid starting state दे सकते हैं — बिना अलग से हर field set किए।
class Student {
String name;
Student(String n) { name = n; }
}
Student s1 = new Student("Aarav");- Class-जैसा special method
- new होते ही auto-call होता है
- Initial values set करता है
Default constructor कोई arguments नहीं लेता और fields को default values (0, null, false) पर set करता है — अगर तुम ख़ुद कुछ नहीं लिखते तो Java automatically एक "no-arg" constructor दे देता है (इसे ही "default constructor" कहते हैं, technically)।
Parameterized constructor arguments लेता है ताकि object को तुरंत meaningful starting values दी जा सकें — real projects में ज़्यादातर classes parameterized constructor ही use करती हैं, क्योंकि "खाली" object शायद ही कभी useful होता है।
ज़रूरी बात: अगर तुम ख़ुद कोई constructor (parameterized या no-arg) लिखते हो, Java automatic default constructor देना बंद कर देता है — अगर तुम्हे दोनों चाहिए (no-arg और parameterized), दोनों explicitly लिखने पड़ेंगे।
class Student {
String name;
Student() { name = "Unknown"; } // no-arg
Student(String n) { name = n; } // parameterized
}एक class में multiple constructors हो सकते हैं, different parameters (number या type) के साथ — जैसे Java के built-in classes में होता है (new ArrayList() या new ArrayList(20) या new ArrayList(anotherList) दोनों valid हैं)। इससे object बनाने के multiple flexible तरीक़े मिलते हैं, caller अपनी situation के हिसाब से choose कर सकता है।
class Rectangle {
int width, height;
Rectangle() { this(1, 1); } // default: 1x1
Rectangle(int side) { this(side, side); } // square
Rectangle(int w, int h) { width = w; height = h; }
}this(...) से एक constructor दूसरे constructor (उसी class के) को call कर सकता है — duplicate initialization code avoid करने के लिए। ऊपर वाले Rectangle example में देखो, कैसे हर छोटा constructor बड़े को call कर रहा है।
super(...) से child class का constructor parent class के constructor को call करता है — ताकि parent का setup पहले हो जाए।
दोनों का एक strict rule है: ये call constructor की *बिल्कुल पहली* line होनी चाहिए — ना तो दोनों एक साथ लिख सकते हो (this() और super() एक ही constructor में नहीं हो सकते), ना इनसे पहले कोई और code।
class Student {
String name; int age;
Student(String name) { this(name, 18); } // chaining
Student(String name, int age) { this.name = name; this.age = age; }
}Constructor class के नाम से जुड़ा होता है, इसलिए child class parent के constructor को directly inherit नहीं करती — ये एक common confusion है। लेकिन child अपने constructor में super(...) के through parent का constructor call कर सकता है, और अगर child कुछ ना लिखे, Java automatically super() (parent का no-arg constructor) call करता है default behavior में।