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 :
- 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 :Ruby123class Carattr_accessor :make, :model, :colorend
- Creation of object of a class
The object of a class is used to access the data members of the class.
For Example :Ruby1car1=Car.new
- 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 :Ruby12345car1.make='Honda'car1.model='Civic'car1.color='Blue'
- Create the methods of the class
In this we will create the methods of the class.
For Example :Ruby12345class Cardef driveprint 'Driving'endend
- Accessing the methods of the class
Object is used to access the methods of the class.
For Example :Ruby1print car1.drive
- Implementing Inheritance of class
- 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 :Ruby12345678class Vehicleattr_accessor :make, :color, :yearendclass Car < Vehicleattr_accessor: fourwheelend
- Accessing the attributes with the help of child class objectRuby123456car1=Car.newcar1.make='BMW'car1.color='Black'car1.year=2012car1.fourwheel='No'
- Making another child class to inherit the parent class
Example :Ruby123456789class Boat < Vehicleattr_accessor :hullendboat1=Boat.newboat1.make='Sampleboat'boat1.color='White'boat1.year=2009boat1.hull='fibreglass'
- Creating method in the child class
Example :Ruby1234567891011class Car < Vehicledef dodonutsprint'Doing Donuts'endendclass Boat < Vehicledef sailingprint 'Im Sailing'endend
- Accessing the methods
Only the object of the child class can access its own member and the parent class member.Ruby123print car1.dodonutsprint boat1.sailing