Inheritance

Inherited classes allow for similar code to be re-used, this saves on code space and also development/testing time. Inherited classes basically have access to the internals of the “super” inherited class.

To create a inherited class
class sibling < superclass

And the sibling class can then call any methods etc within the superclass. The code example explains in code 😉

# base "Books" class
class Books
   # this is called within the .new class call
   def initialize(name, author, year)
       @name = name;
       @author = author;
       @year = year;
   end
 
   def to_s
          # return the to_s (to_string)
          "Books - Name #{@name} - Author #{@author} - Year #{@year}"
   end          
end
 
# this class is Inherited from the "Books" class
class BookToCD < Books
    def initialize(name, author, year, cdID)
           # use the "Books" class initlialize to setup the local variables within the super/inherited class
           super(name, author, year)
           #setup the local variables
           @cdID = cdID
    end
 
    def to_s
           # get the result from the super class
           result = super.to_s
           # return the result from the super class + the local cdID variable
           return result + " - CDID #{@cdID}" 
    end
end
# create a book
book = Books.new("Programming in Ruby", "Ruby Team", 2006)
# inspect outputs the internel structure of the class
puts book.inspect
puts book.to_s
 
booktocd = BookToCD.new("CD read of programming in Ruby", "Ruby Team",2006, 1)
# the inspect shows that the new class has a different memory address
puts booktocd.inspect
puts booktocd.to_s

Once executed on the command line the result is

#<Books:0x2777070 @year=2006, @name="Programming in Ruby", @author="Ruby Team">
Books - Name Programming in Ruby - Author Ruby Team - Year 2006
#<BookToCD:0x2776f38 @year=2006, @name="CD read of programming in Ruby", @cdID=1, @author="Ruby Team">
Books - Name CD read of programming in Ruby - Author Ruby Team - Year 2006 - CDID 1

As you can see the inspect method is showing that the memory block of the book and also booktocd are not the same even though they are sharing the same internals, this is Object Orientated.

Leave a Reply

Your email address will not be published. Required fields are marked *