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

Class के Basics

एक class एक blueprint है जो describe करता है कि एक kind की चीज़ें क्या जानती हैं और क्या कर सकती हैं, जैसे किसी toy car का plan। आप इसका उपयोग जितनी चाहें उतनी toy cars बनाने के लिए करते हैं।

In this page:

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

markup
class Dog(name: String) {
  def bark(): Unit = {
    println(s"$name says Woof!")
  }
}

object Main extends App {
  val rex = new Dog("Rex")
  rex.bark()
}
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. Scala 2 में new के बिना एक object बनाना, जैसे किसी plain class के लिए Dog("Rex"), जो compile नहीं होता; सिर्फ case classes को apply मिलता है।
  2. किसी plain constructor parameter के लिए rex.name call करना, जो class के लिए private है जब तक इसे val के रूप में declare न किया जाए।
  3. 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:

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.