# What are Object Oriented Principles?
Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” to design applications and computer programs. It is based on several key principles: Encapsulation, Abstraction, Inheritance, and Polymorphism. Let’s dive into each of these principles with examples:
1. Encapsulation
Encapsulation is the concept of bundling the data (attributes) and methods (functions) that operate on the data into a single unit, or class. It also involves restricting direct access to some of the object’s components, which is a means of preventing accidental interference and misuse of the data.
Example:
class Car
def initialize(make, model, year)
@make = make
@model = model
@year = year
end
def details
"#{@year} #{@make} #{@model}"
end
end
my_car = Car.new("Toyota", "Corolla", 2020)
puts my_car.details # Output: 2020 Toyota CorollaIn this example, the Car class encapsulates the attributes make, model, and year, and provides a method details to access them.
2. Abstraction
Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object. It helps in reducing programming complexity and effort.
Example:
class CoffeeMachine
def make_coffee
boil_water
brew_coffee
pour_in_cup
end
private
def boil_water
puts "Boiling water..."
end
def brew_coffee
puts "Brewing coffee..."
end
def pour_in_cup
puts "Pouring coffee into cup..."
end
end
machine = CoffeeMachine.new
machine.make_coffeeHere, the CoffeeMachine class abstracts the process of making coffee. The user only needs to call make_coffee without worrying about the underlying steps.
3. Inheritance
Inheritance is a mechanism where a new class inherits the properties and behavior of an existing class. It promotes code reusability.
Example:
class Animal
def speak
"Hello!"
end
end
class Dog < Animal
def speak
"Woof!"
end
end
dog = Dog.new
puts dog.speak # Output: Woof!In this example, the Dog class inherits from the Animal class but overrides the speak method.
4. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It is achieved through method overriding and method overloading.
Example:
class Shape
def area
raise "This method should be overridden by subclasses"
end
end
class Circle < Shape
def initialize(radius)
@radius = radius
end
def area
Math::PI * @radius**2
end
end
class Rectangle < Shape
def initialize(length, width)
@length = length
@width = width
end
def area
@length * @width
end
end
shapes = [Circle.new(5), Rectangle.new(4, 6)]
shapes.each { |shape| puts shape.area }
In this example, both Circle and Rectangle classes inherit from the Shape class and implement the area method. The shapes array can hold objects of both classes, and calling area on each object will invoke the appropriate method.
These principles help in creating modular, reusable, and maintainable code.