Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Inheritance in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 210
    Comment on it

    One of the fundamental aspects of Object-oriented programming is inheritance. Inheritance lets a class inherit properties from another class. Child class acquires behaviours from its parent class. This means the child classes will automatically have parent class methods, without having to implement them.

     

    We use inheritance to keep common behaviors in a parent class and share with child classes. This way we can keep common logic in one place. Ruby support single inheritance

     

    Example:

    class Person
      attr_accessor :name, :dob, :address
    
      def initialize(name, dob, address)
        @name = name
        @dob = dob
        @address = address
      end
    
      def profession
        "Nothing"
      end
    end
    
    
    class Teacher < Person
      def profession
        'teaching'
      end
    end
    
    
    class Doctor < Person
      def profession
        'doctor'
      end
    end
    
    
    a = Doctor.new("ravi", "4 Nov", "India")
    a.name # => "ravi"
    a.dob # => "4 Nov"
    a.profession # => 'doctor'

     

    Here the Parent class is super class. Teacher and Doctor classes are inheriting from Parent class. Child classes acquire behaviors  (initialize, getter and setter methods)  from its parent class. We have overridden "profession" method in child classes.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: