Ruby - OOPs Concepts

1. Introduction

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which contain data and methods to work with the data. Ruby is a powerful OOP language that offers classes, objects, methods, inheritance, and more.

OOPs Concepts:

The core concepts of OOP in Ruby include:

1. Classes and Objects: The blueprints for creating objects (instances) containing methods and properties.

2. Methods: Functions defined inside a class that describe the behaviors of an object.

3. Inheritance: A mechanism for creating new classes that are based on existing classes.

4. Encapsulation: The bundling of data and the methods that work on that data.

5. Abstraction: Hiding the internal implementation details and showing only the necessary features.

6. Polymorphism: The ability to call the same method on different objects and have each of them respond in their own way.

2. Program Steps

1. Define a base class.

2. Create a subclass that inherits from the base class.

3. Demonstrate encapsulation and abstraction.

4. Show polymorphism through method overriding.

3. Code Program

# Define a base class
class Animal
  def initialize(name)
    @name = name  # Encapsulation, instance variable is encapsulated inside the class
  end
  def speak  # Polymorphism, base method to be overridden
    "Generic animal sound"
  end
end
# Inheritance
class Dog < Animal
  def speak  # Method overriding to demonstrate polymorphism
    "#{@name} says Woof!"
  end
end
# Abstraction
class Cat < Animal
  private
  def secret_life_of_cats  # Abstract method, not accessible outside
    "Dreaming of chasing mice"
  end
  public
  def speak
    "#{@name} says Meow! " + secret_life_of_cats
  end
end
# Instantiate objects
dog = Dog.new("Buddy")
cat = Cat.new("Whiskers")
# Call methods
puts dog.speak
puts cat.speak

Output:

Buddy says Woof!
Whiskers says Meow! Dreaming of chasing mice

Explanation:

1. We define a base class Animal with an initialize method and a speak method.

2. Dog and Cat are subclasses that inherit from Animal.

3. The @name instance variable is encapsulated within the Animal class.

4. The speak method is overridden in the Dog and Cat classes to demonstrate polymorphism. The Dog class returns a different string from the Cat class, even though the method name is the same.

5. secret_life_of_cats in the Cat class is an example of abstraction. This method is private and cannot be accessed outside of the class.

6. When we call speak on instances of Dog and Cat, they behave according to their class definitions, showing polymorphism.


Comments