Inheritance (annotated)

Preview:

Citation preview

INHERITANCE IN RUBYSavannah Worth

Uses of inheritance:

Help organize our classes

Reduces repetition in our code

Help create specific classes that inherit general behavior

What is a class in Ruby?

An enclosed set of behaviors (methods) and data (instance variables)

A class in ruby contains a method table

Planet !!!!!!

Methods: !

noun !

Class Pointer

Method Table

Inheritance is a way for a class to gain access to the methods of another class

Terminology:

Parent-child

Superclass-subclass

Parent

Child Classes

Planet

IceGiant GasGiant RockyPlanet

EXAMPLE!

IceGiant Planet

neptune.noun

neptune = IceGiant.new

Methods: !

material

Methods: !

noun

<earth = Planet.new

earth.material

Planet

X

What happens if we make a method in the

child class with the same name as a

method in the parent class?

EXAMPLE!

IceGiantMethods:

material noun

PlanetMethods:

!

noun

neptune.noun

neptune = IceGiant.new

<

Planet

If we want to call the parent class’s method of the same name, we can use the super keyword.

EXAMPLE!

IceGiantMethods:

!material

noun (super)

PlanetMethods:

!

noun

neptune.noun

neptune = IceGiant.new

<

Planet

Ruby has single inheritance*—a class can only have one parent.

CelestialBody

Planet

IceGiant

But you can inherit from a class that’s

inheriting from

another!

Parent of Planet

Parent of IceGiant and Child of

CelestialBody

Child of Planet

*You can model multiple inheritance using modules

CelestialBody

Planet

IceGiant

neptune = IceGiant.newmethods

orbit

neptune.orbit

When and why do we use inheritance?

Useful for general classes that branch off into more specific classes

Child classes get the higher functionality and also can add their own.

Reduces repetition and makes changing our code easier

Inheritance is not always the right tool

Good for “is-a” type relationships

Not as good for “has-a” type relationships.

@SavannahDWorth

Recommended