The "Objective-C for Java Programmers, Part 1" intro by David Chisnall states that
Because you can have multiple base classes, Objective-C introduces the
id type to represent a pointer to some kind of object. You can
implicitly cast between any object type and id.
To the best of my understanding, Objective-C is single-inheritance (just like Java, but unlike C++).
So what does "multiple base classes" mean (in this context)?
It means that you can define your own root or "base" class.
#interface MyRootClass
#end
Note that it does not inherit from NSObject.
In practice, this is never done because said class can't really be used inter-operably with the rest of the system APIs because they all expect NSObject inherited behavior.
That isn't really the motivation behind the id type, though. The id type means, quite literally, this object reference can be an instance of any class.
That there may be multiple base classes is entirely orthogonal.
No, implementing the NSObject #protocol isn't really good enough.
Related
From Apple's own website: "At the heart of Swift's design are two incredibly powerful ideas: protocol-oriented programming and first class value semantics."
Can someone please elaborate what exactly is protocol oriented programming, and what added value does it bring?
I have read this and watched the Protocol-Oriented Programming in Swift video, but coming from an Objective-C background still haven't understood it. I kindly ask for a very plain English answer along with code snippets & technical details about how it's different from Objective-C.
Just one of the confusions I have is using <tableViewDelegate, CustomDelegate> Couldn't we also conform to multiple protocols in Objective-C as well? So again how is Swift new?
EDIT: See Protocol-Oriented Views video. I find this video to be more basic and easier to grasp a meaningful use case. The WWDC video itself is a bit advanced and requires more breadth. Additionally the answers here are somewhat abstract.
Preface: POP and OOP are not mutually exclusive. They're design paradigms that are greatly related.
The primary aspect of POP over OOP is that is prefers composition over inheritance. There are several benefits to this.
In large inheritance hierarchies, the ancestor classes tend to contain most of the (generalized) functionality, with the leaf subclasses making only minimal contributions. The issue here is that the ancestor classes end up doing a lot of things. For example, a Car drives, stores cargo, seats passengers, plays music, etc. These are many functionalities that are each quite distinct, but they all get indivisibly lumped into the Car class. Descendants of Car, such as Ferrari, Toyota, BMW, etc. all make minimal modifications to this base class.
The consequence of this is that there is reduced code reuse. My BoomBox also plays music, but it's not a car. Inheriting the music-playing functionality from Car isn't possible.
What Swift encourages instead is that these large monolithic classes be broken down into a composition of smaller components. These components can then be more easily reused. Both Car and BoomBox can use MusicPlayer.
Swift offers multiple features to achieve this, but the most important by far are protocol extensions. They allow implementation of a protocol to exist separate of its implementing class, so that many classes may simply implement this protocol and instantly gain its functionality.
It surprised me that none of the answers mentioned value type in POP.
To understand what is protocol oriented programming, you need to understand what are drawbacks of objected oriented programming.
It (Objc) has only one inheritance. If we have very complicated hierarchy of inheritance, the bottom class may have a lot of unnecessary state to hold.
It uses class which is a reference type. Reference type may cause code unsafe. e.g. Processing collection of reference types while they are being modified.
While in protocol oriented programming in swift:
It can conform multiple protocols.
It can be used by not only class, but also structures and enumerations.
It has protocol extension which gives us common functionality to all types that conforms to a protocol.
It prefers to use value type instead of reference type. Have a look at the standard swift library here, you can find majority of types are structures which is value type. But this doesn't mean you don't use class at all, in some situation, you have to use class.
So protocol oriented programming is nothing but just an another programming paradigm that try to solve the OOP drawbacks.
In Objective C protocol is the same thing as interface in most languages. So in Objective C protocol's usage is limited to SOLID principle "Depend upon Abstractions. Do not depend upon concretions."
In Swift protocols were improved so seriously that since they still could be used as interfaces in fact they are closer to classes (like Abstract classes in C++)
In Objective C the only way to share functionality between classes is an inheritance. And you could inherit the only one parent class. In Swift you could also adopt as many protocols as you want. And since protocols in Swift can have default methods implementation they give us a fully-functional Multiple inheritance. More flexibility, better code reuse - awesome!
Conclusion:
Protocol Oriented Programming is mostly the same as OOP but it pays additional attention to functionality sharing not only via inheritance but also via protocol adoption (Composition over inheritance).
Worth to mention that in C++ abstract classes are very similar to protocols in Swift but no one says C++ supports some specific type of OOP. So in general POP is a one of the versions of OOP if we speak about programming paradigms. For Swift POP is an improved version of OOP.
Adding to the above answer
Protocol is a interface in which signature of methods and properties are declared and any class/struct/enum subclassing the enum must have to obey the contract means they have to implement all the methods and properties declared in superclass protocol.
Reason to use Protocol
Classes provide single inheritance and struct doesn't support inheritance. Thus protocols was introduced.
Extension The methods declare inside the protocol can be implemented inside the extension to avoid the redundancy of the code in case protocol is being inherited in multiple class / struct having same method implementation. We can call the method by simply declaring the object of struct/enums. Even we can restrict the extension to a list of classes, only restricted class will be able to use the method implemented inside the extension while rest of the classes have to implement method inside own class.
Example
protocol validator{
var id : String{ get }
func capitialise()-> (String)
}
extension validator where Self : test{
func capitialise() -> String{
return id.capitalized
}
}
class test : validator {
var id: String
init(name:String) {
id = name
}
}
let t = test(name: "Ankit")
t.capitialise()
When to use In OOP suppose we have a vehicle base class which is inherited by the airplane, bike, car etc. Here break, acceleration may be common method among three subclass but not the flyable method of airplane. Thus if we are declaring flyable method also in OOP, the bike and car subclass also have the inherit flyable method which is of no use for those class. Thus in the POP we can declare two protocols one is for flyable objects and other is for break and acceleration methods. And flyable protocol can be restricted to use by only the airplane
Protocol Oriented Programming(POP)
protocol-first approach
Protocol as a key point of OOP concept. abstraction, inheritance, polymorphism, encapsulation.
Protocol as a base for SOLID[About]
Protocol instead of class hierarchy tree. Its is hard to support class inheritance. Moreover it has some performance impact
Class/struct can implements multiple protocols(a kind of multiple inheritance)
Composition over inheritance.
extension MyClass: MyProtocol {
}
Default method. Shared implementation for all implementators
extension MyProtocol {
func foo() {
//logic
}
}
Protocol inheritance. One protocol can extends another protocol. Implementator of protocol one should implements all from first and the second protocols
protocol ProtocolB: ProtocolA {
}
value type implement protocol(as usual reference type)[About]
Protocol Oriented Programming (POP)
Came since Swift 2.0
class (OOP)
is reference type
memory leak, incorrect data stored,race condition to access in complex multi-thread environments
can be large by inheriting members of super classes at chain time
struct (POP)
is value type - each time a fresh copy is made when needed
provides multi inheritance - inherits protocols
Protocol :
Defines what Methods, Properties and Initializes are required o Can
inherit another Protocol(s)
Don’t have to use override keyword to implement protocol functions
Extensions:
Default value and
The default implementation for protocol
Can add extra members to
protocol
what is protocol oriented programming? What’s POP?
is a new programming paradigm
we start designing our system by defining protocols. We rely on new concepts: protocol extensions, protocol inheritance, and protocol compositions.
value types can inherit from protocols, even multiple protocols. Thus, with POP, value types have become first class citizens in Swift. value types like enums, structs
*POP lets you to add abilities to a class or struct or enum with protocols which supports multiple implementations.
Apple tells us:
“Don’t start with a class, start with a protocol.”
Why? Protocols serve as better abstractions than classes.
Protocols: are a fundamental feature of Swift. They play a leading role in the structure of the Swift standard library and are a common method of abstraction.
Protocols are used to define a “blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.”
Benefits of Protocol-Oriented Programming:
All classes are decoupled from each other
Separating the concerns of declaration from implementation
Reusability
Testability
One of the most frequently asked questions on iOS developer interview is - difference between abstract classed and interface.
I don't know an answer and i don't get it neither. Interface is a section of class, when you declared methods. it could be open for other classes (public, .h file) or hidden in implementation.
Abstract class is a class, that is only used to create hidden subclasses and it should not have own init methods (if i understand correct).
So, what exactly is answer for that question? And what does that question mean?
I did spend time searching for an answers, but answers wasn't related to Obj-C, so i can't figure out by myself.
I hope someone could provide clear answer and that question would be helpful for those guys, who want to pass an interview.
A good way to approach this problem is first think about it in general programming theory, and then in more concrete Objective-C context.
Abstract Class - is a class intended purely for subclassing, one must not instantiate it. Abstract class declares something and has also the implementation for that.
What is the reason for having such special class? It is modelled after real life! :)
Imagine an abstraction - an animal. What has each animal in common? They are all alive (and can die). They need to eat. The can move in space. These traits are common and fundamental to all animals. I heaven't heard about an animal that doesn't needs food, cannot move and lives forever. Other then that there is a LOT of not so fundamental differences between various animals.
There is no animal on the planet which is purely an abstract animal like that. That set of fundamental behaviours, traits is simply not enough to be a concrete animal..
There is an implied principle, that to be a concrete animal, you have to have some additional traits besides those fundamental ones.
Now, in programming, we need to be able to somehow
express these fundamentals (interface declaration)
have a way of describing how they work (implementation)
attribute them to a class
prevent instantiation
ensure that any concrete animal will have them (inheritance)
We know, what these fundamentals are (declared public interface) and we know in practice how they manifest themselves concretely (implementation of those declared traits). We want them to be inherited by all concrete entities. So we do it in the abstract class because it satisfies these condition I mentioned. It contains all the fundamentals, has their implementation, but cannot be instantiated on its own.
Abstract class is an abstraction over a set of related entities that captures what is fundamentally common between all of them., tells us how it is done..and ensures all more concrete entities will inherit this.
Interface - is something less. Let's a have a real life analogy. Person, robot, animal, wind (a force of nature).
Some people can sing. A robot has a voice synthesizer module embedded so it can sing. The autumn wind touching my teracce glass "sings" a lot I can tell you. And Tinka (r.i.p) my dog, was actually a good singer too.
But really, "singing" between these four has the only thing in common - you can hear it as pleasing sound in your ears. How the singing happens for those four, differs a lot in reality. (implementation)
Another complication is, certainly not all people, dogs, winds, or animals can sing. Some of them can.
So how would we reflect this situation in programming? Via interface :)
You can have an interface called "SingInterface" which in our case has one behaviour/trait/functionality declared and it is sing. Interface simply declares something and that's it. Interface doesn't say how that something is done, there is no concrete implementation. Nor does it say who can do it, the trait in the interface is not limited to one type or one class really. (see http://www.nasa.gov/centers/goddard/universe/black_hole_sound.html)
Interface is a list of 1 to N traits/functionalities without knowing how concretely will they be realized, and that list of traits/functionalities that can be arbitrarily (no rules exist to who) attributable to entities from disparate sets that are fundamentally different (animals or robots).
Object oriented programming borrows many concepts from real life. That's why these analogies work so well.
In Objective C, contrary to some other languages (C# etc),
there is no language level support for abstract classes. It is not possible to enforce that a class is abstract during compilation. A class is abstract only by convention and respecting that convention by developers.
As for interfaces, a word "protocol" is used in objective C. It's just a different word for the same thing.
In objective C you can
code against the interface ..by declaring some object as
id<protocolName>
add additional functionality to classes by declaring that they conform to protocol which you do in the class interface
#interface ClassName <protocolName>
So, there might possibly be even a case where your class is a subclass of abstract class, and it also conform to some protocol.
Thanks to Rob Napier's comment at here. My answer is:
An interface is just the outside view of a class. What it reveals publicly.
In Swift you just write a class in a single .Swift file, and if ask Xcode to show you can generate its interface. Xcode will only then show properties/functions that are public/internal.
In Objective-C. You first have to manually write the interface...declaring what of the class is public and then manually write the implementation. An interface without implementation is not compilable. It's like you saying this is how my class will look like, but then you have provided nothing for how it implements the public methods or how you manipulate your properties—when you must (provide).
Abstract relieves you of how it implements
For abstract classes, you shouldn't provide any implementation, only that it would have such parameters or it would have such functions with such signatures. However an abstract class is compilable on its own. Because you don't need to provide anything more than that.
In the section of code below, what exactly does the <UIScrollViewDelegate> part mean and do? what would it most likely be used for and what would most likely happen if it was removed? (any theoretical example is good)
#interface PhoneContentController : ContentController <UIScrollViewDelegate>
It means that PhoneContentController adopts the ObjC protocol named UIScrollViewDelegate.
A protocol is an interface of methods without definition. When the class adopts it, it advertises that it implements the methods declared by the protocol.
This is a common feature in OOD for an abstract type, particularly in languages which use single inheritance only. If you know Java, it's much like implements UIScrollViewDelegate.
I'm struggling with naming protocols in Objective-C. For example:
I have a protocol called Command.
I have an abstract class that implements Command that is a base class for my concrete Commands.
I believe it is possible to call both the protocol and the base class 'Command' but this is confusing and will cause import clashes if I need to reference the protocol in an implementation. I also understand that in Objective C, using a prefix to denote a protocol is bad form. Some examples use 'ing' added to the end, but in this instance that makes no sense. Calling the abstract class 'CommandBase' seems wrong as well.
So how should I name them?
I would suggest that in your case it is not necessarily bad to name your protocol and the base class the same thing, as your class is the principal expression of the protocol (such as with NSObject).
From Apple's Coding Guidelines for Cocoa: Code Naming Basics:
Some protocols group a number of unrelated methods (rather than create
several separate small protocols). These protocols tend to be
associated with a class that is the principal expression of the
protocol. In these cases, the convention is to give the protocol the
same name as the class. An example of this sort of protocol is the
NSObject protocol. This protocol groups methods that you can use to
query any object about its position in the class hierarchy, to make it
invoke specific methods, and to increment or decrement its reference
count. Because the NSObject class provides the primary expression of
these methods, the protocol is named after the class.
All covered in Apple's Coding Guidelines For Cocoa in the section Code Naming Basics.
The author states:
Protocols should be named according to how they group behaviors:
Most protocols group related methods that aren’t associated with any
class in particular. This type of protocol should be named so that the
protocol won’t be confused with a class. A common convention is to use
a gerund (“...ing”) form:
NSLocking - Good.
NSLock - Poor (seems like a name for a class).
Some protocols group a number of unrelated methods (rather than create
several separate small protocols). These protocols tend to be
associated with a class that is the principal expression of the
protocol. In these cases, the convention is to give the protocol the
same name as the class.
An example of this sort of protocol is the NSObject protocol. This
protocol groups methods that you can use to query any object about its
position in the class hierarchy, to make it invoke specific methods,
and to increment or decrement its reference count. Because the
NSObject class provides the primary expression of these methods, the
protocol is named after the class.
if you will see predefine protocal of uitableview, NSUrlconnection then u will get the name of protocal just like UItabaleviewDelegate and NSUrlconnectionDelegate. ........
Then you can undertand easy which delegate is belong from which class
So u can use your classnameDelegate as protocal name ....thanks
Let's say i have a griffon object that needs to be part of the felidae and bird class.
How do i do it ?
I can only make it inherit from 1 class at a time...
This may help...
Multiple inheritance
There is no innate multiple inheritance (of course some see this as a benefit). To get around it you can create a compound class, i.e. a class with instance variables that are ids of other objects. Instances can specifically redirect messages to any combination of the objects they are compounded of. (It isn't that much of a hassle and you have direct control over the inheritance logistics.) [Of course, this is not `getting around the problem of not having multiple inheritance', but just modeling your world slightly different in such a way that you don't need multiple inheritance.]
Protocols address the absence of multiple inheritance (MI) to some extent: Technically, protocols are equivalent to MI for purely "abstract" classes (see the answer on `Protocols' below).
[How does Delegation fit in here? Delegation is extending a class' functionality in a way anticipated by the designer of that class, without the need for subclassing. One can, of course, be the delegate of several objects of different classes. ]
-Taken from http://burks.brighton.ac.uk/burks/language/objc/dekorte/0_old/intro.htm
Multiple Inheritance in Objective C is not supported. The reason for not supporting this mechanism might be the fact that it would have been too difficult to include in the language or the authors thought it is a bad programming and design decision. However, in various cases multiple inheritance proves to be helpful. Fortunately objective C does provide some workarounds for achieving multiple inheritance. Following are the options:
Option 1: Message Forwarding
Message Forwarding, as the name suggests, is a mechanism offered by Objective C runtime. When a message is passed to an object and the object does not respond to it, the application crashes. But before crashing the objective c runtime provides a second chance for the program to pass the message to the proper object/class which actually responds to it. After tracing for the message till the top most superclass, the forwardInvocation message is called. By overriding this method, one can actually redirect the message to another class.
Example: If there is a class named Car which has a property named carInfo which provides the car’s make, model and year of manufacture, and the carInfo contains the data in NSString format, it would be very helpful if NSString class methods could be called upon the objects of Car class which actually inherits from NSObject.
- (id)forwardingTargetForSelector:(SEL)sel
{
if ([self.carInfo respondsToSelector:sel]) return self.carInfo;
return nil;
}
Source: iOS 4 Developer's cookbook - Erica Sadun
Option 2: Composition
Composition is a cocoa design pattern which involves referencing another object and calling its functionalities whenever required. Composition actually is a technique for a view to build itself based on several other views. So, in Cocoa terminology this is very similar to Subclassing.
#interface ClassA : NSObject {
}
-(void)methodA;
#end
#interface ClassB : NSObject {
}
-(void)methodB;
#end
#interface MyClass : NSObject {
ClassA *a;
ClassB *b;
}
-(id)initWithA:(ClassA *)anA b:(ClassB *)aB;
-(void)methodA;
-(void)methodB;
#end
Source: Objective-C multiple inheritance
Option 3: Protocols
Protocols are classes which contains method to be implemented by other classes who implement the protocol. One class can implement as many as protocols and can implement the methods. However, with protocols only methods can be inherited and not the instance variables.
You can't, per se. But you can have references to as many other objects as you need and you can use multiple protocols.
You can dynamically create a class at runtime and choose the methods of each parent class to inherit. Have a look at the NeXT runtime's documentation here about dynamically creating classes. I did this once just for fun, but I didn't get very far as it gets incredibly messy very quickly.
Edit
It gets more difficult though, because there can only be one superclass, otherwise the keyword super becomes ambiguous.
First, make felidae a subclass of bird. Piece of cake. :-)