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 :class Car attr_accessor :make, :model, :color end
- 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
- 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'
- 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
- Accessing the methods of the class
Object is used to access the methods of the class.
For Example :
print 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 :
class Vehicle attr_accessor :make, :color, :year end class Car < Vehicle attr_accessor: fourwheel end
- 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'
- 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'
- 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
- 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