super Keyword की जानकारी
super वह तरीका है जिससे एक subclass अपने parent class तक पहुंचता है किसी चीज़ का parent का खुद का version उपयोग करने के लिए।
Syntax
class Subclass: Superclass {
var newProperty: Type
init(newProperty: Type, inherited: Type) {
self.newProperty = newProperty
super.init(inherited: inherited)
}
override func method() { super.method() }
}
Calling super.init in a Subclass Initializer
जब एक subclass अपनी खुद की properties जोड़ता है, इसका initializer आमतौर पर पहले उन्हें सेट करता है, फिर superclass को अपनी खुद की properties initialize करने देने के लिए super.init(...) call करता है।
उदाहरण: Calling super.init in a Subclass Initializer
// Define a class `Vehicle`
class Vehicle {
var wheels: Int
init(wheels: Int) {
self.wheels = wheels
}
}
// Define a class `Car`
class Car: Vehicle {
var brand: String
init(brand: String) {
self.brand = brand
super.init(wheels: 4)
}
}
// Declare a constant `car`, set to `Car(brand: "Ford")`
let car = Car(brand: "Ford")
// Print "\(car.brand) has \(car.wheels) wheels" to the console
print("\(car.brand) has \(car.wheels) wheels")
Login to try C/C++/Java/PHP code in the editor
Using super in an Overridden Method
एक override के अंदर super.methodName() उस method का superclass का original implementation call करता है।
उदाहरण: Using super in an Overridden Method
// Define a class `Greeter`
class Greeter {
// Define the function `greet` with no parameters and returning a String
func greet() -> String {
// Return `"Hello"` from this function
return "Hello"
}
}
// Define a class `EnthusiasticGreeter`
class EnthusiasticGreeter: Greeter {
override func greet() -> String {
// Return `super.greet() + "!!!"` from this function
return super.greet() + "!!!"
}
}
// Print `EnthusiasticGreeter().greet()` to the console
print(EnthusiasticGreeter().greet())
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. #}
आम गलतियां
- किसी subclass के custom initializer में
super.init(...)call करना भूल जाना जब superclass का अपना required setup हो। - किसी class के बाहर
superउपयोग करना (जैसे किसी struct में), जहां इसका कोई मतलब नहीं क्योंकि structs inheritance support नहीं करते। - किसी override में गलत point पर
super.method()call करना, जब parent behavior को नए logic से पहले या बाद में चलना था, इसके बजाय नहीं।
चैप्टर सारांश
supercurrent class के immediate superclass को refer करता है।super.init(...)superclass का initializer call करता है, अक्सर inherited properties setup करने के लिए ज़रूरी।super.method()एक overridden method का superclass का version invoke करता है।superसिर्फ एक subclass के अंदर उपयोग किया जा सकता है, कभी बिना superclass वाले class में नहीं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: