Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C subclass that overrides a method in the superclass

In Objective C, if you are subclassing something, and are planning to override a method on the superclass, should you re-declare the superclass method in your subclass @interface?

For example, if you are subclassing UIViewController (e.g. MyViewController), and you are planning to override "viewDidLoad" should you include that method in your MyViewController @interface declaration, or just implement it in MyViewController.m?

In examples I've come across, I've seen it done both ways (re-declaring the method in your subclass interface, or not re-declaring the method). There may not be any functional difference, but what is the best practice?

like image 605
Andy White Avatar asked Apr 21 '09 00:04

Andy White


People also ask

Which method overrides a method in superclass?

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

Can subclass override the methods of superclass?

A subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method.

Can we override Super method?

When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the way by which java achieve Run Time Polymorphism.

Can you override a private method defined in a superclass?

No, we cannot override private or static methods in Java. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared.


1 Answers

I often declare methods that I plan to override in either the public header or at least in a private category. The benefit to this is that you'll get an incomplete class definition warning if you forget to actually override the method... which comes in handy from time to time.

As for when to place it in the public header, that's pretty subjective and probably up to you/your team's coding styles. I usually only redeclare a method in the public header if I plan to radically change what the method is going to do or if I plan not to invoke the super class's version of the method.

like image 183
Jason Coco Avatar answered Sep 25 '22 02:09

Jason Coco