Web Programming TutorialsImplementing Classes & Objects in Ruby on Rails

Implementing Classes & Objects in Ruby on Rails

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. 1

  3. 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
  4. 2

  5. 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'
    
  6. 3

  7. 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
    
  8. 4

  9. Accessing the methods of the class

    Object is used to access the methods of the class.

    For Example :

    print car1.drive
  10. 5

  11. 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. 6

    3. 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'
    4. 8

    5. 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'
    6. 9

    7. 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
      
    8. 10

    9. 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
    10. 11

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -