inheritance (annotated)

20
INHERITANCE IN RUBY Savannah Worth

Upload: savannah-worth

Post on 12-Jul-2015

62 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Inheritance (annotated)

INHERITANCE IN RUBYSavannah Worth

Page 2: Inheritance (annotated)

Uses of inheritance:

Help organize our classes

Reduces repetition in our code

Help create specific classes that inherit general behavior

Page 3: Inheritance (annotated)

What is a class in Ruby?

Page 4: Inheritance (annotated)

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

A class in ruby contains a method table

Page 5: Inheritance (annotated)

Planet !!!!!!

Methods: !

noun !

Class Pointer

Method Table

Page 6: Inheritance (annotated)

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

Page 7: Inheritance (annotated)

Terminology:

Parent-child

Superclass-subclass

Parent

Child Classes

Planet

IceGiant GasGiant RockyPlanet

Page 8: Inheritance (annotated)

EXAMPLE!

Page 9: Inheritance (annotated)

IceGiant Planet

neptune.noun

neptune = IceGiant.new

Methods: !

material

Methods: !

noun

<earth = Planet.new

earth.material

Planet

X

Page 10: Inheritance (annotated)

What happens if we make a method in the

child class with the same name as a

method in the parent class?

Page 11: Inheritance (annotated)

EXAMPLE!

Page 12: Inheritance (annotated)

IceGiantMethods:

material noun

PlanetMethods:

!

noun

neptune.noun

neptune = IceGiant.new

<

Planet

Page 13: Inheritance (annotated)

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

Page 14: Inheritance (annotated)

EXAMPLE!

Page 15: Inheritance (annotated)

IceGiantMethods:

!material

noun (super)

PlanetMethods:

!

noun

neptune.noun

neptune = IceGiant.new

<

Planet

Page 16: Inheritance (annotated)

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

Page 17: Inheritance (annotated)

CelestialBody

Planet

IceGiant

neptune = IceGiant.newmethods

orbit

neptune.orbit

Page 18: Inheritance (annotated)

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

Page 19: Inheritance (annotated)

Inheritance is not always the right tool

Good for “is-a” type relationships

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

Page 20: Inheritance (annotated)

@SavannahDWorth