• 20 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 4/27/23

Learn the concept of inheritance

We can clearly see the benefits which Object-Oriented programming offers. However there’s always more!

 In this chapter we will explore the next fundamental principle of Inheritance!

Introducing Inheritance

Who wouldn't adore this cuteness:

Can you resist to smile?
Smile!

We can describe it as an object with a number of properties:

  • color

  • weight

and methods:

  • eat

  • sleep

  • walk

We can have a comprehensive class describing a puppy, or a dog more generally:

class Dog {
// properties
var color = "brown"
var weight = 20
// methods
func eat() {
}
func sleep() {
}
func walk() {
}
}

That’s cute, how about kittens ;)?

For the most part we can divide humans into two categories: dog lovers and cat lovers.

...
Is there a class for me too?!

So, fair enough, we must have a Cat class!

Cats have color, weight, they can eat, sleep, walk...

See a pattern?

And in real world, both groups - cats and dogs are animals

So, what if instead of having to define two separate classes with repeated components, we create one base class - Animal and implement all the components animals share?!

So, now, instead of separating dogs and cats from the beginning, we have a class called Animal that implements common properties and methods:

class Animal {
// properties
var color = "brown"
var weight = 20
// methods
func eat() {
}
func sleep() {
}
func walk() {
}
}

Then, we can make two more classes (Dog & Cat) that would inherit everything from the Animal class.

The base class, like Animal, is called parent class. And the class that inherits a parent class is called child class. Other terms used for child class: subclass or subtype.

How do we let Swift know that we are creating a subclass and not a new class?

To indicate that we are creating a subclass, we need to make an adjustment in the class declaration by adding the base class name.  In other words, we add the class we are inheriting after the name of a new class, and separate them with a colon (  :  ):

class ChildClassName: ParentClassName {
}

Now we can finally define our puppies and kittens:

class Dog: Animal {
}
class Cat: Animal {
}

Now we can utilize all the common elements defined in Animal class in our subclasses:

// create instances
var myDog = Dog()
var myCat = Cat()
// modify properties
myDog.color = "beige"
myCat.color = "red"
// observe results
print(myDog.color) // beige
print(myCat.color) // red

 But what’s the point? Can’t we just use the animal class?

In some cases, using Animal class directly would serve a purpose, however, each type of an animal has its own unique characteristics, like dogs can bark and cats can meow!

Now we can add those methods individually to respective classes. This way, our Dog class would take advantage of everything already defined in Animal Class PLUS have some unique capabilities. And the same thing for the Cat class of course:

class Dog: Animal {
func bark() {
}
}
class Cat: Animal {
func meow() {
}
}
// utilize subclass specific elements
var myDog = Dog()
var myCat = Cat()
// let them talk!
myDog.bark()
myCat.meow()

This is cool :ninja:!

How about different breeds of puppies and kittens?

The magic doesn't stop here, we can continue subclassing our classes. We can make classes for Bulldogs and Persian cats, so that our first subclasses, Dog and Cat, become parent classes for the new ones respectively:

class Bulldog: Dog {
}
class Persian: Cat {
}

This way we can organize the code through by implementing an inheritance tree and, as a result, avoid repetitions. Here's an example:

Inheritance tree example
Inheritance tree example

Inheritance in iOS

Well, puppies and kittens made an amusing example, how about a day-to-day situation for an iOS developer? There’s no shortage of examples here!

Let’s start with the visual components of an iOS app: there’s a basic view that implements some properties, such as size, position, or background color. And the class is called UIView.

Then, there are labels and buttons..

Guess what?

They also have size, position and background color! And it’s obvious that before they are labels and buttons, they are simply views! The names of those classes are also familiar to you: UILabel & UIView. And now we have established that labels and buttons are, in fact, subclasses:

class UIView {
/* Lots of clever logic */
}
class UILabel: UIView {
/* Lots of clever logic */
}
class UIButton: UIView {
/* Lots of clever logic */
}

An example of non-visual classes in iOS could be a gesture that has multiple subclasses - like taps, touches, swipes and so on.

You haven't dealt with those explicitly just yet, but it won't be long until you start working with them!

Don’t worry if this doesn't sound cristal clear at the moment; you will learn all this in detail in other courses.

The important part is to realize how we can take advantage of the inheritance principle to design more elegant solutions!

What's in it for NeXTDestination?

What's the fun of having unified entertainment options described by only name and cost? There's so much variety we can take advantage of! Let's pick a few categories:

  • Activities - such as horseback riding, golf, chess, bungee jumping (it's virtual anyway :ange:), etc.

  • Arts - museums, expositions, shows, etc.

  • Gastronomy - restaurants, food shows, workshops, etc. 

Let's define some specifics for each of them:

  • Activities:

    • weatherConditions

    • difficulty

    • location

  • Arts

    • genre

    • teaser

    • location

  • Gastronomy 

    • dressCode

    • cuisine

    • location

Your turn now!

Subclass the Entertainment class to accommodate the new entertainment categories (classes). Analyze the elements of the new subclasses and alter the base class if needed.

Try to do it on your own before peeking at the results:

// No scrolling yet!
class Entertainment {
//properties
static let generalOptions = Entertainment.generateGeneralOptions()
var name: String
var cost: Double
var location: String
static func generateGeneralOptions() -> [Entertainment] {
return [Entertainment]()
}
//initializer
init(name: String, cost: Double) {
self.name = name
self.cost = cost
location = ""
}
}
class Activity: Entertainment {
var weatherConditions = ""
var difficulty = ""
}
class Arts: Entertainment {
var genre = ""
var teaser = ""
}
class Gastronomy: Entertainment {
var dressCode = ""
var cuisine = ""
}

Let's review what we've done:

  • Created subclasses for each new entertainment category.

  • Implemented properties for each subclass

  • Identified a new common element (location) and altered the parent class to accommodate the change. Since it appears that each entertainment subclass will need to also have a location, it's reasonable to move it up to the parent class (or, super class ;)).

Well done!

Let's recap!

  • A class (child) can inherit another class (parent). In this case, all properties and methods of the parent class are available in the child class without the child class needing to redefine them.

  • Creating a class that inherits another class is called subclassing or subtyping.

  • Inheritance makes it possible to organize the code through an inheritance tree and, as a consequence, avoid repetitions.

  • To declare a class that inherits from another class, a semicolon is used after the child class name, and is followed by the parent class name:

    class ChildClassName: ParentClassName {
    }

Ever considered an OpenClassrooms diploma?
  • Up to 100% of your training program funded
  • Flexible start date
  • Career-focused projects
  • Individual mentoring
Find the training program and funding option that suits you best
Example of certificate of achievement
Example of certificate of achievement