Pages

Monday, July 13, 2015

Ruby Inheritance, Encapsulation and Polymorphism

Inheritance
Inheritance is a relation between two classes. A child class inherits all the features of its parent class. Methods from the parent can be overridden in the child and new logic can be added.
Usually, inheritance is used to specialize a class. See the following example :
class Document
  def initialize; end

  # logic to deal with any document

  def print
    # logic to print any kind of document
  end
end
class XmlDocument < Document
  # logic to deal with any document

  def print
    # logic to print a xml document
  end
end
A class can only inherit from one class as opposed to c++ where multi-inheritance can be done (not always for the better).
You can however replicate a certain form of multi-inheritance through the use of modules as mix-ins :
module Presenter
  def to_html; end
end
class XmlDocument < Document
  include Presenter
  # can call the method to_html
end
Encapsulation
Encapsulation is the packing of data and functions into a single component.
Encapsulation means that the internal representation of an object is hidden from the outside. Only the object can interact with its internal data. Public methods can be created to open a defined way to access the logic inside an object.
Encapsulation reduce system complexity and increase robustness by decoupling its components.
class Document
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def set_name(name)
    @name = name
  end
end
d = Document.new('name1')
d.set_name('name1')
I can easily change the value of my document name without having to know how the Document class is implemented. At the end, the Document is the one responsible for udpating its internal details.
Polymorphism
In programming languages and type theory, polymorphism  is the provision of a single interface to entities of different types.
Here’s a simple example in Ruby with inheritance :
class Document
  def initialize
  end

  def print
    raise NotImplementedError, 'You must implement the print method'
  end
end
class XmlDocument < Document

  def print
    p 'Print from XmlDocument'
  end

end
class HtmlDocument < Document

  def print
    p 'Print from HtmlDocument'
  end

end
XmDocument.new.print # Print from XmlDocument
HtmlDocument.new.print # Print from HtmlDocument
As you can see, we sent the same message to different object and got different result. The printmethod is a single interface to entities of different types : XmlDocument and HtmlDocument.

No comments:

Post a Comment