Ruby - Using Inheritance to create new class

Introduction

The @name and @description variables are assigned values in the initialize method when a new Thing object is created.

Instance variables generally cannot be directly accessed from the world outside the class itself.

To obtain the value of each variable, you need a get accessor method such as get_name.

In order to assign a new value, you need a set accessor method such as set_name.

Demo

class Thing       
   def initialize( aName, aDescription ) 
     @name         = aName # from   w w  w.j a va  2s .  c  o m
     @description  = aDescription 
   end 
                          
  def get_name 
      return @name 
  end 
                           
  def set_name( aName ) 
      @name = aName 
  end 
                           
  def get_description 
      return @description 
  end 
                           
  def set_description( aDescription ) 
      @description = aDescription  
  end 

end  

class Product < Thing       
    def initialize( aName, aDescription, aValue ) 
        super( aName, aDescription ) 
        @value = aValue 
    end 
                           
    def get_value 
        return @value 
    end 
                           
    def set_value( aValue ) 
        @value = aValue 
    end 
end

Product class is declared:

class Product < Thing  

The left angle bracket < indicates that Product is a subclass, or descendant, of Thing.

It inherits the data (variables) and behavior (methods) from the Thing class.

Since the methods get_name, set_name, get_description, and set_description exist in the ancestor class (Thing), these methods don't need to be re-coded in the descendant class (Product).

The Product class has one additional piece of data, its value (@value).

We have written get and set accessors for this.

When a new Product object is created, its initialize method is automatically called.

A Product has three variables to initialize (@name, @description, and @value), so its initialize method takes three arguments.

The first two arguments are passed, using the super keyword, to the initialize method of the superclass (Thing) so that the Thing class's initialize method can deal with them:

super( aName, aDescription ) 

When used inside a method, the super keyword calls a method with the same name as the current method in the ancestor or superclass.

If the super keyword is used on its own, without any arguments being specified, all the arguments sent to the current method are passed to the ancestor method.

If a specific list of arguments is supplied, then only these are passed to the method of the ancestor class.

Related Topic