Beginners will soon learn how to use object-oriented programming classes and techniques. But the reason is never told to them. But why? What is a programming class?
Simple Answer: Programmers use the class whenever they need more than one item.
Let’s take the example of the popular Candy Crush game.
Classes are like candy factories. Or car factories. You define one thing at a time and let the code generate the number you want!
Is Object-Oriented Programming (OOP)?
OOP or Object-oriented programming = Using classes in programming
Let’s talk about the following first.
1- What is an object?
In code, we combine a group of variables and related methods (functions) into one unit and call that unit an object.
2- What is a class?
Classes are basic maps that define the behavior and information of objects. They allow us to produce and prototype new samples.
3- What is the method?
The sampling method is the behavior of objects.
We know that classrooms act as factories for our objects, enabling us to prototype new ones. What if we want these things to do something?
Here we will use an example to illustrate this abstract concept better:
Suppose we help the Australian government build a plan to care for the koalas. Each koala will have characteristics such as name, age, weight, etc. Imagine having 50 koalas, and we describe each one with five attributes. Without OOP, we will have 250 = 50 * 5 variables. With OOP, we can easily describe it with less code – a 50-sample Koala class. We do not want to repeat a code over and over again…
class Koala
attr_accessor :name, :weight, :age
@@all =[]
def initialize(name)
@name = name
@weight = weight
@age = age
Koala.all << self
end
def self. all
@@all
end
def donation
puts,” Thank you for helping me! “
end
end
So by doing this, we can have the desired number of koalas.
OO design principles:
1- Separation of responsibilities from each other
Do one thing at a time
2- Abstraction and non-repetition
Reuse your code instead of consecutive copy/paste
3- Line restrictions in methods and classes
Methods should not exceed five lines of code, and classes should not exceed 100 lines
OOP benefits:
1- Encapsulation
2- Abstraction
3- Inheritance
4- Polymorphism
There are many sources to explain the four main concepts of OOP, and this is the best video I found on YouTube, and watching it can give you more information about OOP: