← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 1 of 7

Inheritance के Basics

Inheritance एक hand-me-down है: एक नई class को ज़रूरत की हर चीज़ एक पुरानी class से मिलती है। फिर नई class अपने खुद के extras जोड़ती है।

In this page:

  1. Inheritance Basics
Syntax
scala
class ParentClass(param: Type) {
  // members
}

class ChildClass(param: Type) extends ParentClass(param) {
  // additional members
}

Inheritance Basics

एक class class Dog(name: String) extends Animal(name) से दूसरी से inherit करती है, और parent के सभी non-private members पा लेती है। यह "is-a" संबंध को model करता है, जैसे एक Dog एक तरह का Animal होना।

Scala classes के लिए सिर्फ single inheritance को support करता है -- एक class सिर्फ एक direct superclass को extend कर सकती है, हालांकि traits (बाद में कवर किया गया) behavior share करने का एक और तरीका देते हैं।

Note: Scala सिर्फ single class inheritance को support करता है -- जब आपको कई sources से behavior combine करना हो तब traits का उपयोग करें।

उदाहरण: Inheritance Basics

markup
class Animal(val name: String) {
  def eat(): Unit = println(s"$name is eating")
}

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

object Main extends App {
  val rex = new Dog("Rex")
  rex.eat()
  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. parent को constructor argument पास करना भूल जाना, जैसे extends Animal, जबकि extends Animal(name) ज़रूरी है।
  2. class Dog(val name: String) extends Animal(name) declare करना और error पाना क्योंकि name पहले से parent में एक val है।
  3. extends A with B से दो classes को extend करने की कोशिश करना जहां दोनों classes हों, जबकि सिर्फ traits mix in हो सकते हैं।
🔒

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.