3

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 Houses and Cars.

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:

  1. As explained above, or
  2. Create each class without inheritance and then import it into 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.

jscs
  • 63,694
  • 13
  • 151
  • 195
pete
  • 2,980
  • 4
  • 22
  • 34

1 Answers1

4

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

  • Student is a Person -- Inheritance
  • Car is a vehicle -- Inheritance
  • Person has a House -- Composition (ivar or property)
  • Car has a(n) Engine -- Composition (ivar or property)
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • thank you very much that really answers my question and gives me a rule to stick to. It currently seems easier just to keep inheriting every class but as I learn more about Obj-C I'm sure it will make more sence. – pete Apr 30 '12 at 16:03