In this post, we will understand class, object and other object oriented concepts.
Class & Object
A class is a theory which describes a real world object. It describes the data as well as the functionality of the object.
An object is anything that exists in the real world.
A class is created once and from that, we create multiple objects. Hence, class is always singular and its name should also be singular.
Motorola company created a class named Nexus 6. It defines the design and all features of the mobile handset.
All the handsets that are being sold are objects of this class.
A class in Ruby can be created with following syntax:
class ClassName end
An object of this class can be created with following syntax:
object_name = ClassName.new
Methods in Class
Methods in a class represents functionality. There are two type of methods in a class:
- Instance Methods
These methods belongs to instances and should be called by instances only. Instance methods are declared as normal methods inside the class. For example:
def square(x) puts x*x end
- Class Methods
These methods are called by class name directly and have nothing to do with instances. They are also called static methods in languages like Java, C#. Class methods are declared like this:
def self.add(x, y) puts x+y end
So, they save self. are prefix to their names.
Variables in Class
Variables represents data in the class. There are two type of variables:
- Instance variables
These variables belongs to instances. That means, if we create 10 instances, then there will be 10 different instance variables and they may have different values.
Instance variables are declared with @ prefix.
@width, @height, @name
etc. are all instance variables
- Class variables
These variables belongs to class and are created only once no matter how many instances you create. They are also called static variables in languages like Java, C#.
Class variables are declared with @@ prefix.
etc. are all class variables.
The initialize method
This is a special method. It is called automatically when an object of class is created. We may pass arguments to it while creating the object. This is called constructor in languages like Java, C#. It is defined inside class like this:
def initialize(variable1=value1, variable2=value2) .. end
Here value1, value2 .. are default values for variables variable1, variable2 etc.
Let us now check an example:
class Rectangle def initialize(width=0, length=0) # automatically called when object is created @width = width @length = length end def area @length * @width # return @length * @width end end r1 = Rectangle.new # default values 0,0 will be set for width, length r2 = Rectangle.new(4,6) puts r1.area puts r2.area
Here @width and @length are instance variables. Hence there are two copies of each variable that belongs to objects r1 and r2 i.e.
Ruby don’t support constructor overloading. So, we create parametrized constructor and provide default values to variables. If no value gets passed, variables will be assigned default values.
A singleton class have only one object. It is used when we don’t want others to create multiple objects of a class. What could be the purpose of such a class?
Let us say we have a class that has to read configuration settings from external file before getting functional. Now, configuration loading is a lengthy process and may require a good amount of memory. If we create multiple objects of such class, the configuration would be loaded multiple times and will adversely effect application performance.
Hence, we would like to have a single object that read and provides everything about configuration.
To create a singleton class, we have to follow these steps:
- Declare the object as static (@@) inside the class.
- Provide a static method that returns this object.
- Use the following statement inside the class to disallow creation of objects outside the class:
Here is an example of singleton class:
class Sun #make sure initialize comes before declaring the object def initialize @planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"] end @@instance = Sun.new # create static object def self.instance @@instance # return the object end def planets puts @planets end private_class_method :new end s = Sun.instance s.planets
Inheritance allow one class to inherit features from another class. This is also called is a relationship.
For example: Labrador is a Dog
Inheritance allows code re-usability. If we inherit from existing class (base class), then our class (sub class) object will have its own features as well as features from the base class.
A class can inherit from one existing class with following syntax:
class NewClass < ExistingClass
Let us check an example:
In this example, we will create two class Labrador and Pomeranian. Since, both of them are dogs, we will create a base class Dog that contains common method(s) for both.
class Dog def speak puts "Barks" end end class Labrador < Dog def nature puts "Intelligent and fun loving dog" end end class Pomeranian < Dog def nature puts "Small but barks too much" end end simba = Labrador.new tommy = Pomeranian.new simba.speak simba.nature tommy.speak tommy.nature
Overriding in Inheritance
Sometimes during inheritance, we don’t want a method from base class to exist in the sub class. Though we cannot remove that method, we can hide it. This can be done by creating the same method in sub class (called method overriding). In the next example, we will create classes Penguin, Zebra and Dog. All of them are animals but Zebra and Dog walks on 4 legs whereas Penguin walks on 2 legs.
class Animal def walk_style puts "Walks on 4 legs" end end class Dog < Animal def nature puts "Wild as well as domestic" end end class Zebra < Animal def nature puts "Wild" end end class Penguin < Animal def nature puts "Wild" end # override this method, penguins walks on 2 legs def walk_style puts "Walks on 2 legs" end end simba = Dog.new zeb = Zebra.new pen = Penguin.new simba.walk_style simba.nature zeb.walk_style zeb.nature pen.walk_style pen.nature
Calling base class methods in overriding
What if we wish to override a base class method as well as call it. For this, we have to create method alias in sub class for base class method like this:
alias_method :alias_of_parent_class_method, :base_class_method
Here is an example of Monkey class:
class Monkey < Animal alias_method :animal_walk_style, :walk_style def nature puts "Wild" end def walk_style puts "Walks on 2 legs" animal_walk_style # call base class method end end
*Note: Ruby don’t have the concept of abstract class and interface.