Re: Abstract classes and methods
Re: Abstract classes and methods
- Subject: Re: Abstract classes and methods
- From: Greg Titus <email@hidden>
- Date: Tue, 28 Aug 2001 22:39:56 -0700
On Tuesday, August 28, 2001, at 09:47 PM, Chris Gehlker wrote:
On 8/29/01 8:54 PM, "stuartbryson" <email@hidden> wrote:
In C++ it is possible to force both classes and methods to be
abstract.
That is classes that cannot be instantiated without being subclassed
and
particular methods overrided. How do I force abstract classes and
methods in Obj-C.
AFAICT you can't. And you wouldn't want to if you could. Remember, pure
virtual classes occur at the top of inheritance trees to define the
interface to the tree. But in ObjC every class is a descendent of
NSObject:
you never define the top of the tree.
Well you _can_ define a base class that inherits from nothing, of
course - it's just pretty rare. And even a class which is farther down
in the inheritance tree could still be abstract - it isn't that uncommon
to have an abstract subclass of a concrete base class. But, any time
when you are thinking in terms of an abstract super class in
Objective-C, you should probably consider whether a protocol would be a
better idea.
Anyway, like many things in Objective-C abstract classes and methods
aren't built in to the language, but it isn't hard to implement them if
you want to:
We define a simple little function in our lowest level framework:
void OBRequestConcreteImplementation(id self, SEL _cmd)
{
[NSException raise:OBAbstractImplementation
format:@"%@ needs a concrete implementation of %s", [self class],
sel_getName(_cmd)];
}
Then to make an abstract method, just:
- myMethod
{
OBRequestConcreteImplementation(self, _cmd);
}
(Of course, you could just raise an exception directly in the method
instead of using a separate function for that purpose.)
To make an abstract class, just make sure that you are never alloced:
+ alloc
{
if (self == [MyAbstractClass class])
[NSException raise: @"Nope!" format:@"Can't allocate
MyAbstractClass. It's abstract. Didn't you notice the name of the class?
What kind of programmer are you, anyway?"];
return [super alloc];
}
Again, like many things in Objective-C, this gives you the error at run
time instead of compile time. But accidently allocating an abstract
class is really a rare programming error, at least in my experience.
Hope this helps,
--Greg