Class के Basics
एक class एक blueprint है जो describe करता है कि एक kind की चीज़ें क्या जानती हैं और क्या कर सकती हैं, जैसे किसी toy car का plan। आप इसका उपयोग जितनी चाहें उतनी toy cars बनाने के लिए करते हैं।
In this page:
Syntax
class ClassName {
// fields
// methods
}
val instance = new ClassName
Class Basics
एक Scala class को class ClassName { ... } से declare किया जाता है, जो data और behavior को एक blueprint में बांधता है जिसे आप new से instantiate करते हैं।
कुछ languages के विपरीत, किसी class के primary constructor parameters को सीधे class signature में declare किया जा सकता है, जैसे class Point(x: Int, y: Int)। Scala में हर value, numbers सहित, technically किसी class का एक object है।
Note:
class signature में सीधे declare किए गए constructor parameters आम मामले के लिए एक अलग explicit constructor block की ज़रूरत से बचाते हैं।
उदाहरण: Class Basics
class Dog(name: String) {
def bark(): Unit = {
println(s"$name says Woof!")
}
}
object Main extends App {
val rex = new Dog("Rex")
rex.bark()
}
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. #}
आम गलतियां
- Scala 2 में
newके बिना एक object बनाना, जैसे किसी plain class के लिएDog("Rex"), जो compile नहीं होता; सिर्फ case classes कोapplyमिलता है। - किसी plain constructor parameter के लिए
rex.namecall करना, जो class के लिए private है जब तक इसेvalके रूप में declare न किया जाए। object Main extends Appके अंदरclass Dog { def bark = ... }का उपयोग करना और इसके methods call करने से पहले इसे instantiate करना भूल जाना।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: