Reputation: 2485
Lets say I have a Deck class which is based on NSObject. We also have PlayingCardDeck which is based on the Deck class.
How is the method bellow legal ?
-(Deck *) createDeck
{
return [[PlayingCardDeck alloc]init];
}
Upvotes: 0
Views: 37
Reputation: 726569
Yes, a method can return a different type, as long as it is compatible with the one specified.
We have
PlayingCardDeck
which is based on theDeck
class.
Then it is perfectly OK to return an instance of PlayingCardDeck
, because it is a Deck
.
This technique is very important and popular in OOP. It lets you hide the implementation, and expose the interface. For example, you could make several implementations of Deck
, but let your users know of only the top-level Deck
class. This gives you flexibility in choosing an implementation without breaking your users' code.
Cocoa framework also uses this concept a lot. For example, some methods of NSString
declared with the return type of NSString
actually return a subclass of NSString
. Since user code does not need to know about the subclass, they can conveniently write NSString
, and program to its interface.
Upvotes: 1
Reputation: 1566
Supposing you coded the object inheritance correctly: yes, it is legal because your PlayingCardDeck is indeed a Deck.
Upvotes: 1