Reputation: 3050
When creating classes, is there a rule for when to use inheritance and when to import a new class, without inheritance, into another?
Here’s an example:
I make a class called Person
, and then create lots of Person
objects.
I then create a child class called House
. Using inheritance and properties, all my Person
objects can now have a House
.
I then create a child class called Car
so all my Person
objects now have House
s and Car
s.
and so on… and so on….
I now have this sequence of classes:
NSObject < Person < House < Car < new Class < another new Class, etc.
With the above scenario, my logic (I'm an Objective-C beginner) tells me I have two different ways of producing the same outcome:
Person
as an ivar – for example, an instance of House
now becomes a type, and that is then imported into a Person
object using properties.Please excuse my lack of terminology and understanding. If required, I can upload a code example but it’s more of a general question on when and when not to use inheritance.
Upvotes: 3
Views: 154
Reputation: 727137
This question is not specific to Objective-C: the guideline for when to use inheritance is the same for all object-oriented languages, and it is based on substitutability, summarized by the Liskov Substitution Principle:
if S is a subtype of T, then objects of type T may be replaced with objects of type S
In other words, use inheritance only when you can say "{derived} is a {base}>"; when you model a "{owner} has a {something}", use composition
Upvotes: 4