Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects,” which can contain data in the form of fields (often known as attributes or properties) and code in the form of procedures (often known as methods). OOP aims to implement real-world entities like inheritance, polymorphism, encapsulation, and abstraction in programming.
Object-Oriented Programming gas three key aspects: i) it uses objects, not algorithms, as fundamental logical building blocks, ii each object is an instance of a class, and iii) classes can relate to each other via inheritance relationships. If any of these three elements is missing, the program is not truly object-oriented.
Key Concepts of OOP
-
Class: A blueprint for creating objects. It defines a datatype by bundling data and methods that work on the data into one single unit. Object: An instance of a class. It is a self-contained component that contains properties and methods needed to make a certain type of data useful.
-
Encapsulation is the mechanism of restricting access to some of the object’s components and protecting the object’s internal state from unauthorized access. This is typically achieved through access modifiers like private, protected, and public. Inheritance:
-
Inheritance is a mechanism where a new class inherits properties and behavior (methods) from an existing class. This promotes code reuse and establishes a natural hierarchy between classes.
-
Polymorphism allows methods to do different things based on the object it is acting upon, even though they share the same name. It can be achieved through method overriding (runtime polymorphism) and method overloading (compile-time polymorphism).
-
Abstraction is the concept of hiding the complex implementation details and showing only the necessary features of an object. It helps in reducing programming complexity and effort.
Here’s a simple example to illustrate OOP concepts in Ruby:
# Define a class
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
def speak
"Hello, I am an animal."
end
end
# Define a subclass that inherits from Animal
class Dog < Animal
def speak
"Woof! My name is #{@name}."
end
end
# Create an object of the Dog class
dog = Dog.new("Buddy")
puts dog.speak # Output: Woof! My name is Buddy.
In this example:
- Class and Object: Animal is a class, and dog is an object of the Dog class.
- Inheritance: Dog inherits from Animal.
- Polymorphism: The speak method is overridden in the Dog class.
- Encapsulation: The name attribute is accessed and modified through getter and setter methods (attr_accessor).
Summary
Object-Oriented Programming (OOP) is a paradigm that uses “objects” to design applications and computer programs. It leverages key concepts like classes, objects, encapsulation, inheritance, polymorphism, and abstraction to create modular, reusable, and maintainable code.