Inheritance क्या है
Inheritance एक class को दूसरी class के एक special version के रूप में बनने देता है, अपने आप इसकी सभी properties और abilities पाते हुए।
In this page:
Syntax
class Superclass {
var property: Type
func method() { }
}
class Subclass: Superclass {
func newMethod() { } // inherits everything above
}
Basic Class Inheritance
class Dog: Animal लिखना Dog को Animal का एक subclass बनाता है, अपने आप इसकी सभी properties और methods inherit करते हुए।
उदाहरण: Basic Class Inheritance
// Define a class `Animal`
class Animal {
var name: String
init(name: String) {
self.name = name
}
// Define the function `describe` with no parameters and returning a String
func describe() -> String {
// Return `"\(name) is an animal"` from this function
return "\(name) is an animal"
}
}
// Define a class `Dog`
class Dog: Animal {
}
// Declare a constant `dog`, set to `Dog(name: "Rex")`
let dog = Dog(name: "Rex")
// Print `dog.describe()` to the console
print(dog.describe())
Login to try C/C++/Java/PHP code in the editor
Adding New Members in a Subclass
एक subclass इसके inherit की हर चीज़ से आगे पूरी तरह नई properties और methods introduce कर सकता है।
उदाहरण: Adding New Members in a Subclass
// Define a class `Animal`
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
// Define a class `Dog`
class Dog: Animal {
// Define the function `bark` with no parameters and returning a String
func bark() -> String {
// Return `"\(name) says Woof!"` from this function
return "\(name) says Woof!"
}
}
// Declare a constant `dog`, set to `Dog(name: "Rex")`
let dog = Dog(name: "Rex")
// Print `dog.bark()` to the console
print(dog.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. #}
आम गलतियां
- यह भूल जाना कि Swift में सिर्फ classes inheritance support करते हैं; structs और enums किसी दूसरे struct या enum से inherit नहीं कर सकते।
- एक साथ एक से ज़्यादा class से inherit करने की कोशिश करना; Swift classes के लिए सिर्फ single inheritance allow करता है (protocols के विपरीत, जो multiple conformance support करते हैं)।
- यह भूल जाना कि
finalकिसी class को बिल्कुल subclass होने से रोकता है, जो performance और API design के लिए उपयोगी है।
चैप्टर सारांश
- एक subclass
class Sub: Superउपयोग करके अपने superclass से properties और methods inherit करता है। - Swift classes सिर्फ single inheritance support करते हैं -- एक direct superclass।
- किसी class पर
finalकिसी भी आगे की subclassing को रोकता है। - एक subclass इसके inherit की चीज़ों से आगे नई properties और methods जोड़ सकता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: