Object-oriented programming (OOP) is a way of writing computer code that focuses on creating "objects." These objects are like digital versions of things we see in the real world. Just as real objects have characteristics and can do things, OOP objects have data and functions built into them.
Let's break OOP down into key concepts:
Abstraction allows programmers to create simplified models of real-world objects or processes, making code easier to understand and maintain. It's often considered one of the fundamental principles of OOP alongside encapsulation, inheritance, and polymorphism.
OOP helps organize code, makes it easier to reuse, and can make complex programs simpler to understand and maintain.
# Abstraction and Encapsulation
class Vehicle
def initialize(brand)
@brand = brand # Encapsulated instance variable
end
def start_engine
puts "Engine starting..."
end
# Abstract method
def move
raise NotImplementedError, "You must implement the move method"
end
end
# Inheritance
class Car < Vehicle
def initialize(brand, model)
super(brand)
@model = model
end
# Encapsulation: Getter method
def info
"#{@brand} #{@model}"
end
# Polymorphism: Implementing the abstract method
def move
puts "Car is driving on the road"
end
end
# Another class for Polymorphism example
class Boat < Vehicle
def move
puts "Boat is sailing on the water"
end
end
# Creating objects
my_car = Car.new("Toyota", "Corolla")
my_boat = Boat.new("Yamaha")
# Using objects
puts my_car.info # Output: Toyota Corolla
my_car.start_engine # Output: Engine starting...
my_car.move # Output: Car is driving on the road
my_boat.move # Output: Boat is sailing on the water
# Polymorphism
vehicles = [my_car, my_boat]
vehicles.each { |vehicle| vehicle.move }
This code demonstrates:
my_car
and my_boat
are objects.Vehicle
, Car
, and Boat
are classes.Car
and Boat
inherit from Vehicle
.@brand
are private, accessed through methods.Car
and Boat
implement move
differently.Vehicle
provides an abstract move
method.These concepts describe different ways objects can be related to each other in OOP, helping to model complex systems and relationships more accurately.