View
245
Download
2
Category
Tags:
Preview:
Citation preview
Uses of inheritance:
Help organize our classes
Reduces repetition in our code
Help create specific classes that inherit general behavior
An enclosed set of behaviors (methods) and data (instance variables)
A class in ruby contains a method table
Terminology:
Parent-child
Superclass-subclass
Parent
Child Classes
Planet
IceGiant GasGiant RockyPlanet
IceGiant Planet
neptune.noun
neptune = IceGiant.new
Methods: !
material
Methods: !
noun
<earth = Planet.new
earth.material
What happens if we make a method in the
child class with the same name as a
method in the parent class?
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
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.
Recommended