Possible Duplicate:
Creating an abstract class in Objective C
I'd like to make abstract class in Objective-C project.
But, I can't find ideas suchlike 'abstract'(in java), 'virtual'(in c++).
Doesn't Objective-C have an abstract idea? Thank you.
Possible Duplicate:
Creating an abstract class in Objective C
I'd like to make abstract class in Objective-C project.
But, I can't find ideas suchlike 'abstract'(in java), 'virtual'(in c++).
Doesn't Objective-C have an abstract idea? Thank you.
Formally, no. Abstract classes are implemented by stubbing out methods in the base class and then documenting that a subclass must implement those methods. The onus is on the author to write classes that match the class contract rather than on the compiler to check for missing methods.
Objective-C has protocols, which are like Java interfaces. If you're looking for the equivalent to a pure virtual C++ class or an interface in Java, this is what you want.
There are no abstract classes but you can produce something similar using a combination of a class and a protocol (which is similar to Java's interface). First divide up your abstract class into those methods you wish to provide default implementations for and those you require sub-classes to implement. Now declare the default methods in an @interface
and implement them in an @implementation
, and declare the required methods in an @protocol
. Finally derive your sub-classes from class<protocol>
- a class which implements the protocol. For example:
@interface MyAbstract
- (void) methodWithDefaultImplementation;
@end
@protocol MyAbstract
- (void) methodSubclassMustImplement;
@end
@implementation MyAbstract
- (void) methodWithDefaultImplementation { ... }
@end
@interface MyConcreteClass: MyAbstract<MyAbstract>
...
@end
@implementation MyConcreteClass
// must implement abstract methods in protocol
- (void) methodSubclassMustImplement { ... }
@end
If you are concerned over using the same name for a class and a protocol look at Cocoa where NSObject
follows this pattern...
HTH