[Swift] Inheritance rules for constructor init

Summarize:

1. The subclass does not customize the designated constructor -> [inherit all parent class constructors, including designated and convenience constructors]

2. The subclass customizes the designated constructor and overloads the designated constructor of the parent class [only inherits the convenience constructor of the parent class]

3. The subclass custom designated constructor does not overload the designated constructor of the parent class [does not inherit any constructor of the parent class]

 

Automatic Inheritance of Constructors

As mentioned above, subclasses do not inherit superclass constructors by default. But if certain conditions are met, the parent class constructor can be automatically inherited. In fact, this means that you don't have to override the superclass's constructor for many common scenarios, and can inherit the superclass's constructor with minimal cost when it is safe.

Assuming you provide default values ​​for all new properties introduced in subclasses, the following 2 rules will apply:

rule 1

If the subclass does not define any designated initializers, it will automatically inherit all designated initializers from the parent class.

Rule 2

If the subclass provides implementations of all of the superclass's designated initializers —whether inherited via rule 1 or provides a custom implementation—it will automatically inherit all of the superclass's convenience initializers.

These two rules still apply even if you add more convenience initializers to your subclasses.

Notice

Subclasses can implement rule 2 by implementing the superclass's designated initializer as a convenience initializer.

Based on the official case reference:

class Food {
    var name: String
    init(name: String) {
        self.name = name
    }
    
    convenience init(type:String) {
        self.init(name: "[Unnamed]")
    }
}

class RecipeIngredient: Food {
    var quantity: Int
    init(name: String, quantity: Int) {
        self.quantity = quantity
        super.init(name: name)
    }
    override convenience init(name: String) {
        /*
            1、重载了父类的指定构造器且使用了便利构造器的方式
            2、满足了【重载父类指定构造器】的条件,则自动继承父类全部便利构造器!
         */
        self.init(name: name, quantity: 1)
    }
}

class ShoppingListItem: RecipeIngredient {
    /*
        1、子类没有定义任何指定构造器,它将自动继承父类所有的指定构造器。
     */
    var purchased = false
    var description: String {
        var output = "\(quantity) x \(name)"
        output += purchased ? " ✔" : " ✘"
        return output
    }
}

Guess you like

Origin blog.csdn.net/weixin_43343144/article/details/130283409