rb612
rb612

Reputation: 5563

Why do we override initializers in Swift?

From Swift's documentation:

Unlike subclasses in Objective-C, Swift subclasses do not inherit their superclass initializers by default.

But then it says:

When you write a subclass initializer that matches a superclass designated initializer, you are effectively providing an override of that designated initializer. Therefore, you must write the override modifier before the subclass’s initializer definition.

Coming from a Java background where constructors are not inherited, I don't understand how this works exactly. Why would we be overriding an initializer that isn't inherited by default? It seems to me like constructors, initializers would be implicitly named after the class itself and can be overloaded in the subclass (for example, class Dog in Java would only have constructors with name Dog). But I don't understand this idea of overriding a parent initializer.

Upvotes: 4

Views: 520

Answers (1)

Rob
Rob

Reputation: 437582

Subclasses might not inherit their superclass initializers "by default", but they can be inherited (e.g. if you don't supply any designated initializers, you will automatically inherit all of the designated initializers of the superclass ... see Automatic Initializer Inheritance).

Consider a Dog subclass called Chihuahua: If you don't implement any designated initializers in Chihuahua, you automatically inherit the Dog initializers with no extra code on your part. But if you do need to override it for some reason, do so and you just need to call a Dog designated initializer from your Chihuahua designated initializer. And if your Chihuahua initializer has the same signature as a Dog designated initializer, then you must explicitly supply the override keyword.

Upvotes: 1

Related Questions