Inheritance के Basics
Inheritance एक hand-me-down है: एक नई class को ज़रूरत की हर चीज़ एक पुरानी class से मिलती है। फिर नई class अपने खुद के extras जोड़ती है।
In this page:
Syntax
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
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()
}
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. #}
आम गलतियां
- parent को constructor argument पास करना भूल जाना, जैसे
extends Animal, जबकिextends Animal(name)ज़रूरी है। class Dog(val name: String) extends Animal(name)declare करना और error पाना क्योंकिnameपहले से parent में एकvalहै।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: