Search code examples
objective-cclassinitializationoverridingdesignated-initializer

Override designated initializer of superclass


I am reading a book which has a guideline:

"If a class declares a designated initializer that is different from its superclass, the superclass’s designated initializer must be overridden to call the new designated initializer"

As I understand this guideline in other words is that, if I am subclassing my class form its superclass, and my subclass has a designated initializer which is different from des. initializer of its superclass, then in my subclass I must override the designated initializer of my superclass and inside it call the designated initializer of my subclass.

Is this true? Do we have to do this all the time? Thank you.


Solution

  • @justin is basically on the point.

    Methods in Objective-C are inherited. That means if the superclass has an initializer method (initializers are just methods), and your subclass does not override it, then your subclass will inherit that superclass's initializer method. That means that people can always call that superclass's initializer on an object of your subclass (basic consequence of inheritance and subtype polymorphism). But that might not be what you expected. The superclass's initializer might not do all the initialization that your class needs.

    That's why you should override the superclass's initializer. If you don't want people to use that initializer on an object of your class, you should throw an exception in that initializer. Otherwise, you should override it to do any appropriate initialization for your class.