Method Overriding क्या है
Overriding तब है जब एक subclass अपने parent की किसी ability को अपने custom version से replace करता है।
In this page:
Syntax
class Subclass: Superclass {
override func methodName() -> ReturnType {
return value // replaces the parent version
// or: super.methodName() // call the parent version
}
}
Overriding a Method
किसी subclass में override func उपयोग करना inherited method के implementation को एक नए से replace करता है।
उदाहरण: Overriding a Method
// Define a class `Animal`
class Animal {
// Define the function `makeSound` with no parameters and returning a String
func makeSound() -> String {
// Return `"Some generic sound"` from this function
return "Some generic sound"
}
}
// Define a class `Cat`
class Cat: Animal {
override func makeSound() -> String {
// Return `"Meow"` from this function
return "Meow"
}
}
// Declare a constant `cat`, set to `Cat()`
let cat = Cat()
// Print `cat.makeSound()` to the console
print(cat.makeSound())
Login to try C/C++/Java/PHP code in the editor
Calling super in an Override
किसी override के अंदर, super.method() call करना parent class का original implementation चलाता है, आपको इसे पूरी तरह replace करने के बजाय extend करने देते हुए।
उदाहरण: Calling super in an Override
// Define a class `Animal`
class Animal {
// Define the function `describe` with no parameters and returning a String
func describe() -> String {
// Return `"An animal"` from this function
return "An animal"
}
}
// Define a class `Cat`
class Cat: Animal {
override func describe() -> String {
// Return `super.describe() + " that says Meow"` from this function
return super.describe() + " that says Meow"
}
}
// Declare a constant `cat`, set to `Cat()`
let cat = Cat()
// Print `cat.describe()` to the console
print(cat.describe())
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. #}
आम गलतियां
- किसी inherited method को फिर से define करते समय
overridekeyword भूल जाना; Swift accidental overrides रोकने के लिए इसे explicitly चाहता है। finalचिह्नित किसी property या method को override करने की कोशिश करना; Swift compile करने से मना कर देगा।- एक method override करना लेकिन
super.method()call करना भूल जाना जब parent का behavior अब भी नए behavior के साथ चलना चाहिए।
चैप्टर सारांश
- किसी inherited method या property को override करने के लिए explicit
overridekeyword चाहिए। finalकिसी method, property, या class को override या subclass होने से रोकता है।super.method()override के अंदर से parent class का original implementation call करता है।- Overriding एक subclass को inherited behavior को इसे जैसा है वैसा reuse करने के बजाय customize करने देता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: