Sunteți pe pagina 1din 9

Azi povestim despre OOP sau Object Oriented Programming care este o paradigma des intalnita in programare.

Foarte multe limbaje de programare populare suporta OOP. Printre ele as aminti Java, C++, C#, Python, PHP, JavaScript,
Ruby, Perl, Objective-C, sau Swift.

Aceste limbaje care suporta OOP au la baza cateva concepte precum Clasele care sunt niste templaturi si Obiectele care sunt instante ale acestor clase. De exemplu putem sa avem o Clasa numita Persoana si pe baza ei sa creem mai
multe Obiecte care vor fi practic niste persoane, adica Obiectul Radu, Mihai sau Cristina. Dar despre Clase si Obiecte vom invata mai multe in videoul viitor care va fi practic, in JS.

Vrei sa inveti WordPress, GIT sau Security Testing?


Vezi aceste cursuri in limba Romana.

OOP se bazeaza pe 4 mari principii. Daca intelegem aceste principii ne va fi usor sa intelegem si aceasta paradigma si modul in care putem implementa viitoarele proiecte. Hai sa le luam pe rand.

1. Abstractizarea este procesul prin care “ascundem” anumite functionalitati pe care nu e nevoie sa le stii. De exemplu, atunci cand lucrezi intr-o echipa de programatori ai putea primi un task in care e nevoie sa creezi
functionalitatea de salvare in baza de date. Ceilalti colegi vor folosi functionalitatea ta de foarte multe ori cand vor salva lucruri in baza de date. Ei bine, ei nu trebuie sa stie exact cum salvezi tu acele date, cum ai scris codul si ce se
intampla mai exact in functionalitatea ta. Ei pur si simplu vor folosi functionalitatea ta trimitand datele in baza de date cu un efort minim. In acest mod, codul aplicatiei devine oarecum modular, adica format din bucatele de sine
statatoare care fac anumite lucruri bine definite.
2. Incapsulare este procesul prin care tinem datele si functiile separate de exterior. Daca luam tot exemplul precendent in care tu faci functionalitatea de adaugare in baza de date, e posibil ca acolo sa ai niste variabile
in care sa tii username-ul si parola de conectare la baza de date. Ei bine, nu ai vrea ca o alta functionalitatea sa poata modifica variabila username sau din gresala ea sa fie suprascrisa de un username folosit in zona de creare useri. Prin
incapsulare creem o capsula care delimiteaza interiorul de exterior.

3. Mostenirea sau Inheritance da voie unor clase sa preia proprietati din alte clase. Un exemplu bun pentru a explica mostenirea este cazul unei aplicatii prin care vindem masini. Aceste masini au in general aceleasi
proprietati cu unele mici diferente. Toate vor avea un anumit tip de combustibil, capacitate cilindrica a motorului sau pret. Diferenta vine atunci cand ne intereseaza numarul de locuri in cazul unui autoturism si masa maxima de
transport in cazul unui camion. In codul nostru, vom avea nevoie de 2 clase si anume Car si Truck care au destul de multe proprietati in comun. Ca sa nu duplicam proprietatile acestea putea sa creem o clasa principala numita Vehicle
care va avea proprietatile comune si apoi clasele Car si Truck care vor mostenii Vehicle si vor avea in plus proprietatile specifice.

4. Polimorfism este procesul prin care putem sa creem mai multe copii ale aceleiasi metode care poate sa primeasca inputuri diferite. Ca exemplu practic putem sa luam aici din nou un site de vanzari auto. Am stabilit
mai inainte ca avem nevoie de o clasa Vehicle si in ea vrem sa creem o metoda care sa ne aduca toate informatiile unei masini pe baza numarul de inmatriculare. In acelasi timp vrem sa putem face acest lucru si pe baza seriei de sasiu.
Ei bine aceste 2 date sunt diferite ca format si lungime asa ca avem nevoie de 2 metode, cu acelasi nume care primesc inputuri diferite dar afiseaza acelasi lucru.

Mai multe resurse:

 http://codebetter.com/raymondlewallen/2005/07/19/4-major-principles-of-object-oriented-programming/

 https://medium.freecodecamp.org/object-oriented-programming-concepts-21bb035f7260

 https://www.studytonight.com/cpp/cpp-and-oops-concepts.php

Object Oriented Programming in C++


Object Oriented programming is a programming style that is associated with the concept of Class, Objects and various other concepts revolving around these two,
like Inheritance, Polymorphism, Abstraction, Encapsulation etc.
In the video below, we have explained the basic concepts of Object Oriented Programming with help of a very easy to understand example. If you want to skip the
video, everything is covered below as well.

Let us try to understand a little about all these, through a simple example. Human Beings are living forms, broadly categorized into two types, Male and Female.
Right? Its true. Every Human being(Male or Female) has two legs, two hands, two eyes, one nose, one heart etc. There are body parts that are common for Male
and Female, but then there are some specific body parts, present in a Male which are not present in a Female, and some body parts present in Female but not in
Males.

All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs some common functions, but there are some specifics to both, which is
not valid for the other. For example : A Female can give birth, while a Male cannot, so this is only for the Female.

Human Anatomy is interesting, isn't it? But let's see how all this is related to C++ and OOPS. Here we will try to explain all the OOPS concepts through this example
and later we will have the technical definitons for all this.

Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its properties and its functions. Like Human Being, having
body parts, and performing various actions.

Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat, see etc. Male and Female are also classes, but most of
the properties and functions are included in HumanBeing, hence they can inherit everything from class HumanBeing using the concept of Inheritance.

Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being, Male or Female, we just mean a kind, you, your friend, me we are the
forms of these classes. We have a physical existence while a class is just a logical definition. We are the objects.
Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our example, Human Being's can talk, walk, hear,
eat, but the details are hidden from the outside world. We can take our skin as the Abstraction factor in our case, hiding the inside mechanism.

Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk. Our hands, help us hold things. This binding of the properties to
functions is called Encapsulation.

Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done or by changing the parts using which it is
done. Both the ways have different terms for them.

If we walk using our hands, and not legs, here we will change the parts used to perform something. Hence this is called Overloading.

And if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else. Then I can walk like I want, this will be called
as Overriding.

OOPS Concept Definitions


Now, let us discuss some of the main features of Object Oriented Programming which you will be using in C++(technically).

1. Objects

2. Classes

3. Abstraction

4. Encapsulation

5. Inheritance

6. Overloading

7. Exception Handling

Objects
Objects are the basic unit of OOP. They are instances of class, which have data members and uses various member functions to perform tasks.

Class
It is similar to structures in C language. Class can also be defined as user defined data type but it also contains functions in it. So, class is basically a blueprint for
object. It declare & defines what data variables the object will have and what operations can be performed on the class's object.
Abstraction
Abstraction refers to showing only the essential features of the application and hiding the details. In C++, classes can provide methods to the outside world to
access & use the data variables, keeping the variables hidden from direct access, or classes can even declare everything accessible to everyone, or maybe just to
the classes inheriting it. This can be done using access specifiers.

Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class.

Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is called the Base class & the class which inherits is called
the Derived class. They are also called parent and child class.

So when, a derived class inherits a base class, the derived class can use all the functions which are defined in base class, hence making code reusable.

Polymorphism
It is a feature, which lets us create functions with same name but different arguments, which will perform different actions. That means, functions with same name,
but functioning in different ways. Or, it also allows us to redefine a function to provide it with a completely new definition. You will learn how to do this in details
soon in coming lessons.

Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at runtime.
Have you noticed how the same cliche questions always get asked at job interviews — over and over again?

I’m sure you know what I mean.

For example:

Where do you see yourself in five years?

or, even worse:

What do you consider to be your greatest weakness?

Ugh…give me a break. I consider answering this question a great weakness! Anyway, not my point.

As trivial as questions like these may be, they are important because they give clues about you. Your current state of mind, your attitude, your
perspective.

When answering, you should be careful, as you may reveal something you later regret.

Today I want to talk about a similar type of question in the programming world:

What are the main principles of Object-Oriented Programming?

I’ve been on both sides of this question. It’s one of those topics that gets asked so often that you can’t allow yourself to not know.

Junior and entry-level developers usually have to answer it. Because it’s an easy way for the interviewer to tell three things:

1. Did the candidate prepare for this interview?

Bonus points if you hear an answer immediately — it shows a serious approach.

2. Is the candidate past the tutorial phase?

Understanding the principles of Object-Oriented Programming (OOP) shows you’ve gone beyond copy and pasting from tutorials — you already see things from a

higher perspective.

3. Is the candidate’s understanding deep or shallow?

The level of competence on this question often equals the level of competence on most other subjects. Trust me.
The four principles of object-oriented programming are encapsulation, abstraction, inheritance, and polymorphism.
These words may sound scary for a junior developer. And the complex, excessively long explanations in Wikipedia sometimes double the confusion.

That’s why I want to give a simple, short, and clear explanation for each of these concepts. It may sound like something you explain to a child, but I
would actually love to hear these answers when I conduct an interview.

Encapsulation
Say we have a program. It has a few logically different objects which communicate with each other — according to the rules defined in the program.

Encapsulation is achieved when each object keeps its state private, inside a class. Other objects don’t have direct access to this state. Instead, they
can only call a list of public functions — called methods.
So, the object manages its own state via methods — and no other class can touch it unless explicitly allowed. If you want to communicate with the
object, you should use the methods provided. But (by default), you can’t change the state.
Let’s say we’re building a tiny Sims game. There are people and there is a cat. They communicate with each other. We want to apply encapsulation, so
we encapsulate all “cat” logic into a Cat class. It may look like this:

Yo
u can feed the cat. But you can’t directly change how hungry the cat is.
Here the “state” of the cat is the private variables mood, hungry and energy. It also has a private method meow(). It can call it whenever it wants, the other
classes can’t tell the cat when to meow.
What they can do is defined in the public methods sleep(), play() and feed(). Each of them modifies the internal state somehow and may
invoke meow(). Thus, the binding between the private state and public methods is made.
This is encapsulation.

Abstraction
Abstraction can be thought of as a natural extension of encapsulation.

In object-oriented design, programs are often extremely large. And separate objects communicate with each other a lot. So maintaining a large
codebase like this for years — with changes along the way — is difficult.

Abstraction is a concept aiming to ease this problem.

Applying abstraction means that each object should only expose a high-level mechanism for using it.
This mechanism should hide internal implementation details. It should only reveal operations relevant for the other objects.

Think — a coffee machine. It does a lot of stuff and makes quirky noises under the hood. But all you have to do is put in coffee and press a button.

Preferably, this mechanism should be easy to use and should rarely change over time. Think of it as a small set of public methods which any other
class can call without “knowing” how they work.

Another real-life example of abstraction?


Think about how you use your phone:
Cel
l phones are complex. But using them is simple.
You interact with your phone by using only a few buttons. What’s going on under the hood? You don’t have to know — implementation details are
hidden. You only need to know a short set of actions.

Implementation changes — for example, a software update — rarely affect the abstraction you use.

Inheritance
OK, we saw how encapsulation and abstraction can help us develop and maintain a big codebase.

But do you know what is another common problem in OOP design?

Objects are often very similar. They share common logic. But they’re not entirely the same. Ugh…
So how do we reuse the common logic and extract the unique logic into a separate class? One way to achieve this is inheritance.

It means that you create a (child) class by deriving from another (parent) class. This way, we form a hierarchy.

The child class reuses all fields and methods of the parent class (common part) and can implement its own (unique part).

For example:
A
private teacher is a type of teacher. And any teacher is a type of Person.
If our program needs to manage public and private teachers, but also other types of people like students, we can implement this class hierarchy.

This way, each class adds only what is necessary for it while reusing common logic with the parent classes.

Polymorphism
We’re down to the most complex word! Polymorphism means “many shapes” in Greek.

So we already know the power of inheritance and happily use it. But there comes this problem.

Say we have a parent class and a few child classes which inherit from it. Sometimes we want to use a collection — for example a list — which contains
a mix of all these classes. Or we have a method implemented for the parent class — but we’d like to use it for the children, too.

This can be solved by using polymorphism.

Simply put, polymorphism gives a way to use a class exactly like its parent so there’s no confusion with mixing types. But each child class keeps its
own methods as they are.
This typically happens by defining a (parent) interface to be reused. It outlines a bunch of common methods. Then, each child class implements its own
version of these methods.

Any time a collection (such as a list) or a method expects an instance of the parent (where common methods are outlined), the language takes care of
evaluating the right implementation of the common method — regardless of which child is passed.

Take a look at a sketch of geometric figures implementation. They reuse a common interface for calculating surface area and perimeter:
Tri
angle, Circle, and Rectangle now can be used in the same collection
Having these three figures inheriting the parent Figure Interface lets you create a list of mixed triangles, circles, and rectangles. And treat them like
the same type of object.
Then, if this list attempts to calculate the surface for an element, the correct method is found and executed. If the element is a triangle,
triangle’s CalculateSurface() is called. If it’s a circle — then circle’s CalculateSurface() is called. And so on.
If you have a function which operates with a figure by using its parameter, you don’t have to define it three times — once for a triangle, a circle, and a
rectangle.

You can define it once and accept a Figure as an argument. Whether you pass a triangle, circle or a rectangle — as long as they
implement CalculateParamter(), their type doesn’t matter.
I hope this helped. You can directly use these exact same explanations at job interviews.

If you find something still difficult to understand — don’t hesitate to ask in the comments below.

What’s next?
Being prepared to answer one of the all-time interview question classics is great — but sometimes you never get called for an interview.

Next, I’ll focus on what employers want to see in a junior developer and how to stand out from the crowd when job hunting.

Stay tuned.

S-ar putea să vă placă și