Constructors क्या हैं
एक constructor किसी नए object को उसके बनते ही set up करता है, जैसे box से बाहर निकालते ही किसी toy को charge और assemble करना। Scala में setup inputs class name के ठीक बाद जाते हैं।
In this page:
Syntax
class ClassName(param1: Type, param2: Type) {
// code here runs when the object is created
def this() = this(default1, default2) // auxiliary constructor
}
Constructors
किसी class का primary constructor सीधे उसकी parameter list में define होता है, और class body में कोड (method definitions के बाहर) construction के हिस्से के रूप में चलता है।
Auxiliary constructors, जिन्हें def this(...) से define किया जाता है, किसी object को बनाने के वैकल्पिक तरीके प्रदान करते हैं, और आखिरकार primary constructor को call करना ज़रूरी है। ज़्यादातर simple classes को सिर्फ primary constructor चाहिए।
Note:
हर auxiliary constructor (def this(...)) को आखिरकार, सीधे या किसी दूसरे auxiliary के ज़रिए, primary constructor को call करना चाहिए।
उदाहरण: Constructors
class Person(val name: String, val age: Int) {
println(s"Creating a Person: $name")
def this(name: String) = this(name, 0)
}
object Main extends App {
val alice = new Person("Alice", 30)
val baby = new Person("Baby")
println(s"${alice.name}, ${alice.age}")
println(s"${baby.name}, ${baby.age}")
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
thisconstructor को पहले रखना, जबकि एक auxiliary constructor को अपने पहले statement के रूप में primary या किसी पहले वाले constructor को call करना चाहिए।- यह उम्मीद करना कि class body में code हर class के लिए सिर्फ एक बार चलेगा, जबकि यह हर बार एक instance बनने पर चलता है।
- parameter list में
val nameलिखना लेकिनnameको एक अलग variable के रूप में उपयोग करना, जिससे field और parameter के बीच confusion होता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: