← Back to Scala Course | Chapter 7: OOP Basics | Lesson 2 of 7

Constructors क्या हैं

एक constructor किसी नए object को उसके बनते ही set up करता है, जैसे box से बाहर निकालते ही किसी toy को charge और assemble करना। Scala में setup inputs class name के ठीक बाद जाते हैं।

In this page:

  1. Constructors
Syntax
scala
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

markup
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}")
}
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. #}
आम गलतियां
  1. this constructor को पहले रखना, जबकि एक auxiliary constructor को अपने पहले statement के रूप में primary या किसी पहले वाले constructor को call करना चाहिए।
  2. यह उम्मीद करना कि class body में code हर class के लिए सिर्फ एक बार चलेगा, जबकि यह हर बार एक instance बनने पर चलता है।
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.