Implementing Classes & Objects in Ruby on Rails

0
1020

In this session today we will create Classes their objects and then we will try to use OOP’s concept of Inheritance.

  • Hence to implement the following follow the steps given below :
  1. Creating a Simple Class:

    To create a class the class keyword is used. The name of the class should always starts with the capital letter.

    For example :

    class Car
    attr_accessor  :make,  :model, :color
    end
    

  2. Creation of object of a class

    The object of a class is used to access the data members of the class.

    For Example :

    car1=Car.new

  3. Assign values to the class attributes with the help of the object

    In this part we assign i.e. initialise the attributes through the use of object.

    For Example :

    car1.make='Honda'
    
    car1.model='Civic'
    
    car1.color='Blue'
    

  4. Create the methods of the class

    In this we will create the methods of the class.

    For Example :

    class Car
     def drive
     print 'Driving'
     end
     end
    

  5. Accessing the methods of the class

    Object is used to access the methods of the class.

    For Example :

    print car1.drive

  6. Implementing Inheritance of class
    1. Creating the inheritance relationship

      In the example given below the class Vehicle is the parent class and the Car is the child class.
      Here the child class try to access the attributes of the parent class with the help of inheritance.

      Example :

      class Vehicle
       attr_accessor :make, :color, :year
       end
      
      
       class Car < Vehicle
       attr_accessor: fourwheel
       end
      

    2. Accessing the attributes with the help of child class object

      car1=Car.new
      
      car1.make='BMW'
      car1.color='Black'
      car1.year=2012
      car1.fourwheel='No'

    3. Making another child class to inherit the parent class

      Example :

      class Boat < Vehicle
      attr_accessor :hull
      end
      
      boat1=Boat.new
      boat1.make='Sampleboat'
      boat1.color='White'
      boat1.year=2009
      boat1.hull='fibreglass'

    4. Creating method in the child class

      Example :

      class Car < Vehicle
      def dodonuts
      print'Doing Donuts'
      end
      end
      
      class Boat < Vehicle
      def sailing
      print 'Im Sailing'
      end
      end
      

    5. Accessing the methods

      Only the object of the child class can access its own member and the parent class member.

      print car1.dodonuts
      
      print boat1.sailing

LEAVE A REPLY

Please enter your comment!
Please enter your name here