← Back to Scala Course | Chapter 1: Setup & Basics | Lesson 6 of 8

object बनाम class

एक class एक blueprint है जिससे आप कई copies बना सकते हैं, जबकि एक object एक अनोखी चीज़ है। यह cookie cutter और shelf पर रखी एक खास trophy जैसा फर्क है।

In this page:

  1. object vs class
Syntax
scala
class ClassName(param: Type) {
  // instance members
}
val instance = new ClassName(value)

object ObjectName {
  // single instance members
}

object vs class

एक class एक blueprint है जिसे आप new से instantiate करके शायद कई स्वतंत्र objects बना सकते हैं, जबकि एक object सीधे एक single, lazily-initialized singleton instance define करता है -- इसका हमेशा सिर्फ एक ही होता है।

Objects आमतौर पर utility functions, constants, और program entry points (जैसे object Main में देखा गया) के लिए उपयोग होते हैं। एक ही file में एक जैसे नाम वाले class और object एक "companion" जोड़ी बनाते हैं, जिसे बाद के chapter में कवर किया गया है।

Note: एक single shared instance (जैसे utilities या किसी app का entry point) के लिए object का उपयोग करें, और जब आपको कई स्वतंत्र instances चाहिए हों तब class का।

उदाहरण: object vs class

markup
class Counter {
  var count = 0
  def increment(): Unit = { count += 1 }
}

object MathUtils {
  def square(n: Int): Int = n * n
}

object Main extends App {
  val c1 = new Counter()
  val c2 = new Counter()
  c1.increment()
  c1.increment()
  c2.increment()

  println(s"c1.count = ${c1.count}, c2.count = ${c2.count}")
  println(s"MathUtils.square(5) = ${MathUtils.square(5)}")
}
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. new MathUtils से किसी object का instance बनाने की कोशिश करना, जबकि object पहले से ही एक single instance है।
  2. किसी class name पर Counter.increment() call करना, जबकि method को new Counter().increment() जैसे instance की ज़रूरत है।
  3. state की ज़रूरत न होने पर भी utility methods को class में रखना, जिससे आपको एक instance बनाना पड़ता है जिसकी ज़रूरत नहीं; उन्हें object में रखें।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.