object बनाम class
एक class एक blueprint है जिससे आप कई copies बना सकते हैं, जबकि एक object एक अनोखी चीज़ है। यह cookie cutter और shelf पर रखी एक खास trophy जैसा फर्क है।
In this page:
Syntax
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
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)}")
}
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. #}
आम गलतियां
new MathUtilsसे किसीobjectका instance बनाने की कोशिश करना, जबकि object पहले से ही एक single instance है।- किसी class name पर
Counter.increment()call करना, जबकि method कोnew Counter().increment()जैसे instance की ज़रूरत है। - state की ज़रूरत न होने पर भी utility methods को
classमें रखना, जिससे आपको एक instance बनाना पड़ता है जिसकी ज़रूरत नहीं; उन्हेंobjectमें रखें।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: