Reputation: 1152
Lets say we this example:
Class.h:
@interface Class : NSObject
/* No public methods or ivars */
Class.m:
@implementation Class
-(void)methodOne{}
-(void)methodTwo{};
Subclass.h:
@interface Subclass : NSObject
/* No public methods or ivars */
Subclass.m:
@implementation Subclass
/* I want to override methodOne and methodTwo from superclass but can't. They don't show up as methods */
Do you have to explicitly declare methods in the superclass as public in its header file in order to use those in the subclass? I thought that methods in the implementation file only could be overridden.
Upvotes: 0
Views: 612
Reputation: 318804
It's bad practice to override private methods. The whole point of being private is that no one else should rely on them. Private methods are just that - private. Their signature could change, their implementation could change, or they could go away in the future. Any such changes will cause subclasses to break if the subclasses were overriding the private methods. If the method is meant to be overridden then it should be made public and the API should be stable.
If the methods should only be overridden by subclasses and never called by other clients of the base class, then the base class should provide a 2nd header file declaring the methods in a category specifically meant to only be imported and used by subclasses.
A good example of this is the Apple provided class UIGestureRecognizer
. There is a special header file "UIGestureRecognizerSubclass.h" that is only imported by subclasses. See the "Subclassing Notes" section of the docs for UIGestureRecognizer
for more details.
Upvotes: 1
Reputation: 21244
Do you have to explicitly declare methods in the superclass as public in its header file in order to use those in the subclass?
No, the methods do not have to be declared in the superclass header file. They can be declared as part of a class extension.
Using your example, this would look like:
@interface Class(SomeNameOrNot)
-(void)methodOne{}
-(void)methodTwo{};
@end
This can be expressed in two ways: in a header file or as part of an implementation file.
So, for example, if Subclass
and only that class needed to be aware of those selectors, the above class extension would go into Subclass.m
.
If those methods are intended to be used by any subclass of Class
, but are not intended to be public, they might go into a header file that only those subclasses are aware of (i.e. Class_Internal.h
). This is a common way to provide something like Java's protected
access - a set of interfaces available only to subclasses that opt in to using it by importing the private header.
Upvotes: 0