Middle+
What is the difference between protocols and classes in the context of abstract classes?
sobes.tech AI
Answer from AI
A protocol defines a set of requirements for a type (methods, properties, initializers), but does not provide their implementation. A class can implement one or more protocols.
An abstract class (in Swift, this is emulated through classes with unimplemented methods or protocols) is a base class from which other classes inherit. It can contain both abstract (unimplemented) and implemented methods and properties.
Differences:
| Attribute | Protocol | Abstract class (emulation in Swift) |
|---|---|---|
| Multiple inheritance/implementation | A type can implement multiple protocols | A class can inherit from only one class |
| State storage | Cannot have stored properties | Can have stored properties |
| Method implementation | Does not provide implementation | Can contain implemented methods |
| Instance creation | Cannot create an instance of a protocol | Can create an instance of an abstract class (if there are no abstract methods requiring implementation) |