2012-06-27 86 views
4

可能重复:
Creating an abstract class in Objective C在Objective C中模拟抽象类和抽象方法?

在Java中,我喜欢使用抽象类,以确保一堆类具有相同的基本行为,例如:

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(); 

} 

现在如果B类继承自A类,它只需要实现reallyDoIt()

如何在Objective C中做到这一点?这是否可能? Objective C中可行吗?我的意思是Objective C中的整个范例似乎有所不同,例如从我的理解是没有办法禁止覆盖一个方法(比如在Java中使用'final')?

谢谢!

+0

请参阅此主题[http://stackoverflow.com/questions/1034373/creating-an-abstract-class-in-objective-c](http://stackoverflow.com/questions/1034373/creating-an- abstract-class-in-objective-c) –

回答

10

对于不覆盖目标c中的方法没有实际限制。你可以像Dan Lister在他的回答中所建议的那样使用一个协议,但这只是强制执行你的符合类来实现在该协议中声明的某种行为。

一种用于在目标C的抽象类的解决办法是:

interface MyClass { 

} 

- (id) init; 

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

这样就可以防止你的抽象类的方法被调用(但只能在不同于像Java可以检测语言运行时这在编译时)。

+0

谢谢,那其实我在想做的。我只是希望可以通过某种方式在编译时告诉实现继承类的程序员,该方法缺少一个方法,而不是在运行时。 – iseeall

+1

woulrdn't,使整个'如果(自我= [超级初始化]){...}返回自我;'在子类崩溃? – Kris

4

我想你会想要使用一种叫做Protocols的东西。

+2

+1您可能会补充说Objective-C是一种更强烈地依赖于约定而不是规则强制执行的语言。作为一名开发人员,您必须遵守这些惯例才能使事情顺利进行。 –

+5

协议[几乎]等同于Java中的接口。所以这不是OP可能想要的。 – Eimantas

+0

我不认为抽象类和协议完全相同。考虑:动物*鸭= [鸭新];协议不能像这样的超类型。这种结构可以允许动态地将子类作为参数。 – smileBot