Search code examples
objective-cclassmethodsvirtualabstract

Simulate abstract classes and abstract methods in Objective C?


Possible Duplicate:
Creating an abstract class in Objective C

In Java I like to use abstract classes to make sure that a bunch of classes has the same basic behavior, e.g.:

public abstract class A
{
// this method is seen from outside and will be called by the user
final public void doSomething()
{
// ... here do some logic which is obligatory, e.g. clean up something so that
// the inheriting classes did not have to bother with it

reallyDoIt();
}
// here the actual work is done
protected abstract void reallyDoIt();

}

Now that if class B inherits from class A, it only has to implement reallyDoIt().

How to make this in Objective C? Is it at all possible? Is it feasible in Objective C? I mean the whole paradigm seems to be different in Objective C e.g. from what I understand there is no way to forbid overriding a method (like in Java with 'final')?

Thanks!


Solution

  • There is no actual constraint on not overriding a method in objective c. You can use a protocol as Dan Lister suggested in his answer but this is only good to enforce your conforming class to implement a certain behavior declared in that protocol.

    A solution for an abstract class in objective c could be :

    interface MyClass {
    
    }
    
    - (id) init;
    
    - (id) init {
       [NSException raise:@"Invoked abstract method" format:@"Invoked abstract method"]; 
       return nil;
    }
    

    This way you can prevent methods in your abstract class to be invoked (but only at run-time unlike languages like java which can detect this when on compile-time).