pete
pete

Reputation: 3050

Understanding when to use inheritance to allow one class to use instances of another

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.

Upvotes: 3

Views: 154

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

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

  • 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)

Upvotes: 4

Related Questions