Methods को Override करना
Overriding का मतलब है कि एक child class किसी inherited काम को अपने तरीके से करती है, जैसे कोई बच्चा Grandma की recipe को थोड़े बदलाव के साथ अपनाए। Scala में आपको जान-बूझकर override शब्द लिखना चाहिए।
In this page:
Syntax
class ParentClass {
def method_name(): Type = expression
}
class ChildClass extends ParentClass {
override def method_name(): Type = expression
}
Overriding Methods
कोई subclass override def methodName(...) = ... से किसी inherited method के व्यवहार को बदल देता है, और Scala में override keyword *अनिवार्य* है, कुछ languages के विपरीत जहां यह optional या implicit है।
यह ज़रूरत accidental overrides (या typo की वजह से accidental non-overrides) को compile time पर पकड़ती है। super.methodName(...) override के अंदर से parent का version call करता है।
Warning:
किसी inherited method को बदलते समय override keyword छोड़ देना Scala में एक compile error है, उन languages के विपरीत जहां यह optional है।
उदाहरण: Overriding Methods
class Animal(val name: String) {
def speak(): String = "..."
}
class Dog(name: String) extends Animal(name) {
override def speak(): String = "Woof!"
}
object Main extends App {
val rex = new Dog("Rex")
println(rex.speak())
}
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. #}
आम गलतियां
overridekeyword छोड़ देना, जो error देता है क्योंकि method पहले से parent में मौजूद है।- parameter list या return type को इस तरह बदलना कि वह मेल न खाए, जिससे यह override करने के बजाय overload हो जाता है।
- किसी
finalmethod याdefसे किसीvalको override करने की कोशिश करना, जिसकी अनुमति नहीं है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: