What is Object Oriented Programming (OOP) – A Complete Guide
Learn via video courses
You can better understand Object-Oriented Programming also called OOP with help of an example. Suppose you are working on a “Hotel Management System” project for a hotel.
If you think of developing a system using procedural programming (which is based on procedures or routines that contains a series of steps to be carried out for working) then the system can be viewed in terms of work happening in a hotel that is check-in at the hotel, check-out from hotel, manage rooms, manage bookings of room etc.
However, OOP concept revolves around real-world objects and their usages. Thus in OOP, Hotel Management System can be thought of in terms of the objects involved. Now the question arises, What are objects? So objects are the real-world entity around which our system revolves or in other words system is dependent on objects. In the hotel management system what all objects you can think of in a hotel?
– “Room” which can represents the rooms in that hotel
– “Customer” which represents the customer who will visit to the hotel to book room
– “Booking” which can represents the booking of the room which will be done by customer
So, all these objects represent real world entities and make our system similar to real world entities. Thus you can say that the Object-Oriented programming concept views problems in terms of real-world objects.
Now, to describe or represent real-world objects or entities you need Classes. Class is used to bind characteristics(variables) and functionality. When an object is created which belongs to that class, that object has all the characteristics and methods which were defined in the class and has their specific value according to that object.
For example, in the hotel management system, to represent a room object in terms of class you have to define the properties of the room like room_number, room rent etc as well as methods (functions related to it) which are specific to that room only, for example every room in the hotel has CheckIn and CheckOut functionality of its own.
So every room will have some common characteristic properties(which could be number, rent, size, Ac/Non Ac, status) but the values associated (such as 102 room number, 2000 Rs per night, XL size, AC room, Occupied) to these properties will change for every room independently. Such characteristics are referred to as properties of the object, and their values as state.
Similar to the properties, every room will also have some functionalities which will help the system to access, fetch and update the values of the properties of the room. Such as, if a room has Status value equal to ‘Vacant’ and a new guest arrives and occupies that empty room.
The system must update the status of the room from ‘Vacant’ to ‘Occupied’. So, to perform this update, the room must have a functionality, say, ‘toggleStatus’. The functionality of this function will be switching the status of the room between ‘Vacant’ and ‘Occupied’. All these types of functionalities (which update and fetch the characteristics values) are known as methods of the object.
So now concluding a ‘Room’ class will be a blueprint containing the properties and the methods, but the class will not have any state but whenever it’s object is created, the object’s properties will have some values and contain all the functions described in blueprint(class). . You can say that class represents a group of the same or similar type of objects. So, the “Room” class in the hotel management system is used to represent all the rooms of a hotel.
Thus you can say that the OOP(Object Oriented Programming) /concept is a programming paradigm or concept that aims to implement real-world objects. If you can identify the objects in your code which are similar to real life objects and can structure your code accordingly in classes and objects then you can say that OOP principles are used in your code. So classes and Objects are the basic building blocks of the OOP concept. C++, Java, Javascript are major Object Oriented languages.
OOP importance:
In real life, you deal with a lot of objects or entities like a car, bike, animal, etc. So, programmers need software to be similar to real-world entities. Real-world objects have properties such as car model, car size for car, name, age, occupation for human, etc. and real-world entities or objects can do various things like bikes can move, people can walk or eat, etc. So OOP concept helps the program to be closer to real-world objects. Also, OOP allows code to be reusable and make it more simple. For example, you don’t have to define each room in the hotel management system every time, you can use OOP, to create a class for the room and use it whenever required.
OOP concepts:
These are basic concepts or characteristics of OOPS. We will take a deeper look at each one:
Class A class can be considered as a blueprint or template for creating similar types of objects. Classes are a user-defined data type that defines two things:
- Attributes or data
- Behavior or methods
Individual objects are then created using the class or blueprint.
For example, in the hotel management system mentioned above, you can create a class “Room” to define each room in the hotel which will have attributes and behavior of each room. So room class can contain the following fields or attributes:
– room_number
– room_rent
– room_status
And “Room” class can contain following methods to use above given fields:
– checkIn() : This function will be used to checkin in the room.
– checkout() : This function will be used to checkout of the room.
– getRoomStatus() : This function will give the status of the room whether it is occupied or not.
So “Room” class here is a template to represent a room in the hotel and you have to create or instantiate the Room class to represent an individual real-world thing that is a room of the hotel.
In C++ class is defined using the “class” keyword and then its name is there followed by the body of class in curly braces ending with a semicolon. So to represent class for a room, here is the syntax:
The body of the class will contain methods and data related to Room.
Object
As described at the starting of the article, Objects are real-world entities that contain specific data or information, so you can say that objects are instances of classes that contain specific data or information related to that object. For example, we have defined the “Room” class to represent a hotel room. So to create an instance or object of the “Room” class you have to define an object for the “Room” class which represents a specific room of the hotel. In C++ to define object syntax is as follows:
Suppose you have to define room r1, so r1 will contain all the information specific to that room in the hotel. So to define room r1 for the hotel you can instantiate the “Room” class or create the object of Room class like this:
So, here r1 is an instance or object of class Room and will have its specific room_number, room_rent, room_status.
Note: Whenever you define a class, only the properties of the object are defined, no memory is allocated. So to allocate memory and to use data and functions of a class you have to create objects of that class.
Methods and Attributes
Methods: Methods are functions that are defined in class body or definition and they can perform various actions like updating the field or data of the object of the class, showing the data of the object of the class, etc. Methods generally specify the behavior of a class. When the objects of a class are created, these objects can call the methods of the class. In the above example of Room class,
– checkIn()
– checkOut()
– getRoomStatus()
These are the methods that are defined in the class and these can be called using the objects of class “Room”.
Methods usually promote the reusability of code. Suppose, there is a piece of code that is used in code many times, so instead of writing the same code again and again you can put that code into methods and you can use that method. It also helps programmers to debug the code easily. The programmer has to check errors only at one place that is in the method instead of checking the whole code.
Attributes : Attributes are the data fields or information that are specific to an object. When an object of a class is created all the information specific to that object is stored in attributes or fields. In the above example of Room class,
– room_number
– room_rent
– room_status
These are attributes defined in the “Room” class. Suppose you create object r1 of Room class, then you can store information related to that particular room r1 in the attributes mentioned above.
Note: You can use the “.” operator to access the attributes of objects or you can use getters and setters for objects.
Encapsulation
Encapsulation is a mechanism in which attributes and behaviors are bound together in a class. You can think of Encapsulation as just like a medicine capsule in which many medicines are combined or bound together. Similarly, encapsulation binds data and methods in a class together. Also, Encapsulation provides a function of a secure layer by hiding the software or product internal implementation of code and internal data of the class and exposing only required information to the outer world.
Methods and data are defined in the class definition. Whenever an object of that class will be created, the data and methods are encapsulated or combined in that object or capsule. Just like in our “Room” class of “Hotel Management System” data and methods are bind together in one object.
In Encapsulation, the data of a class is inaccessible for any other outer classes or outer world and only the members of the same class can access that data. In encapsulation, the programmer requires to define some fields or data as public or private:
– Public: These methods or variables(fields) are accessible both from the same class as well as from outer classes also.
– Private: These methods or variables(fields) are accessible only in the same class.
You can take an example: Suppose in the above example of “Hotel Management System” you only want room_rent variable of “Room” class to be accessible only in that Room class or want that no method from any other class can change the rent of that particular room, then we can declare that room_rent field to be “private” so that no one outside the class “Room” can change its value.
Also here we are making the room_rent variable or field private so it can only be changed by the function of the same class. As we are hiding data from outer classes or the world, Encapsulation is also known as Data hiding.
Inheritance
As the name suggests, inheritance is a mechanism in which one class can inherit the property of another class. In other words, the child class can inherit the property of the parent class. It’s just like a child-parent relationship in real life where a son or daughter is inherited by the properties of their parents.
Inheritance promotes the reusability of code. If you want to create a new class and that class has some fields or code common to another class, you can use that class as the parent class and can inherit that class. So in this way, you don’t have to write that same piece of code again and can use that code in the child class or class which you are creating. Hence that code is reused.
The syntax for inheritance is
You can take the example of that “Hotel Management system” which we have discussed in the above examples also. In that system, Rooms in the hotel can be of many types: deluxe rooms, AC rooms, Non AC rooms, Single room, Double room, etc. All rooms are subtypes of class Room or have some fields common to the class “Room” like room_rent, room_status, etc, it’s just like they can have some extra fields or methods. So here we can create child classes for parent class “Room” and all that child classes will inherit that “Room” class. This is the concept of inheritance.
Abstraction
Abstraction involves showing only necessary details to the user and hiding irrelevant details or unnecessary details from the user. It is an extended form of Encapsulation and also serves a security purpose. As complex code is hidden from the user so it becomes easier for the user to use that software and also that software is easier to maintain.
You can take a real-life example of a laptop or computer which you are using. On a laptop you can see the screen, use the keyboard and type something, you can use the mouse pad and can do all your work on the laptop. But do you know its internal details, how that keys are working and how the motherboard of the laptop is working, and how the picture is showing up on the screen? So here, all the internal implementation of the laptop is hidden from the user and it is separated from its external interface. You can use the laptop without knowing its internal implementation. So abstraction provides simple and easy-to-use interfaces for the user.
Polymorphism
Polymorphism means one thing has different forms. Polymorphism allows a member function of a class to behave differently based on the object that will call it. Polymorphism occurs when classes are related through inheritance.
You can take an example:
Suppose there is a function playInstrument() in parent class “Instrument” and Instrument class have two child classes or sub-classes: “Guitar“ and “Trumpet” and playInstrument will return the sound produced by the instrument which will call that function. So if the Guitar class object will call playInstrument then Guitar sound will be the output and if the Trumpet class object will call playInstrument then Trumpet sound will be the output.
Polymorphism can be achieved through function overloading and function overriding.
- Function overriding: In function overriding child class can exhibit different implementation of the same function which has been defined in parent class also, according to its usages.
The above example of “Instrument” class is an example of Function overriding.
- Function overloading: Polymorphism is also achieved through function overloading. In function overloading, methods can have the same name but the number of arguments is different in function calls. Results will be different according to the number of arguments with which the function is called.
You can take a real-life example. Suppose you created a function to calculate areas of a figure to calculate the area of rectangle and square. As you know rectangle area is lengthbreadth and square’s area is sideside so rectangle area function should take 2 arguments length and breadth whereas square area will take one argument that is side.
So instead of creating functions with separate names, you can create two functions with the same name but the number of arguments is different for both functions.
findArea(3) call will go to 1 function as the number of arguments in function is one and findArea(2,5) call will go to 2 function as the number of arguments in the function call is two. This is the concept of function overloading.
Association
Association shows the relationship between two separate classes which establishes through the objects of classes. As discussed above in message passing, that in OOPS an object can communicate to the other object to use their functionality or methods. Association shows “HAS-A” relationship between classes. So if we take the example of “Hotel Management System”, if Hotel is class to represent hotel and Room class represents room of hotel then we can show the association between them like this:
Now, Association can be of following types:
– one-to-one: In one-to-one association, only a single object is associated with another object at a time.
– one-to-many: In one-to-many association, one object is associated with one or more than one object at a time.
– many-to-one: In many to one association many objects are associated with a single object at a time.
– many-to-many: In many to many association, many objects are associated with one or more than one object at a time.
Aggregation and Composition are two types of Association. These two have been defined below in detail.
Composition
The “Composition” is a special form of “Association”. As shown in the above figure, the Composition circle is inside the Association circle so it must be having some restrictions over Association. So in Composition child class object is strongly dependent on the parent class object which means if the parent object is deleted then all child objects will also be deleted. In other words, child objects don’t have their own lifecycle. Composition is a stronger relationship. You can take a real-life example of a dog:
A dog has two legs, one tail, two ears, and one nose. So you can think of a dog as a parent class and legs, tail, ears, and nose as child classes of “Dog” class. So if you delete ears or nose class objects then the dog can survive, but if you delete the parent class object that is the dog then there is no point for legs, tail, ears, and nose class objects. So these child class objects will be deleted if the parent class object is deleted.
Note: Child class can exist independently but that child class object which is dependent on parent class object will be deleted if parent class object is deleted.
Aggregation
Aggregation is another form of Association. In Aggregation, child objects have their own lifecycle which means if the parent object is deleted then all child objects can exist independently. But there is child ownership in Aggregation which means if the parent object is deleted then the child object can exist independently but it can’t belong to another parent class object. Aggregation is a weaker relationship. You can take a real-life example:
Suppose a person has 3 things: a computer, a gaming laptop, and a mouse. So, if that person gives his laptop to another person then also that laptop will remain of the first person or person who is the owner of that laptop which means ownership is there. Even if the parent class object is deleted, the child class object that is the laptop here can exist independently but it can’t belong to another class or to the person to whom the owner of the laptop gave the laptop.
So you can say that aggregation is a process in which one class defines another class as an entity and it promotes reusability and represents the “HAS-A” relationship between classes.
Suppose there is a class of “Scaler employee” and which in turn have another class “Address” object which represents the address of Scaler employee so in this way you are reusing the member of address class in scaler employee class and it shows “has-a” relationship between the two classes.
Advantages of Object Oriented Programming:
- OOP concept allows breaking the project or software into smaller modules or chunks so it makes debugging or testing easy for programmers.
- OOP promotes the reusability of code. For example, using inheritance you can use the code of the parent class in the child class and can eliminate the duplicate code.
- OOP systems or software can be scaled easily.
- As OOP provides the concept of data hiding, it allows programmers to develop secure programs or projects in which any unauthorized user can’t invade or attack.
- OOP concept provides the flexibility in writing code using polymorphism, as you can use the same name function to provide its implementation according to your usage or requirements.
- OOP systems are easily maintainable.
How to Structure OOP Programs:
Let’s take a real-life example of the Hotel Management system which we took in starting by extending it further and design an OOP program. Suppose you have to create software for a hotel that can handle all the rooms, their status, bookings, services, payments, then how will you create simple, reusable software to manage the hotel.
As there will be a lot of categories of rooms in the hotel and you have to maintain the status of each room and its booking and payments, so you can use classes and objects for creating the software.
You have to identify real-life objects in the given scenario and club all the object-related information in class and you can use that class by creating objects of that class.
In the given example here is how a programmer can think of creating classes:
– Room class: To manage rooms of the hotel
– Booking class: To manage all booking of the hotel
– Payment class: To manage all operations of payments of bookings
– Customer class: To manage all operations related to the customer who will come to the hotel to book a room.
Now classes are defined programmer can think of defining attributes of each class:
– Room class : room_no, room_category, room_status, room_rent
– Booking class: booking_id, booking_date, booking description
– Payment class : payment_id, payment_amount, payment_customer_id
– Customer class: customer_id_number, customer_name, customer_room_number
These all are the possible attributes which you can take in each class.
Now a programmer can think of adding methods or logic in each class according to his or her use cases or requirements. Suppose in Room class the programmer can add methods like this: checkIn(), checkOut(), getRoomStatus() and so on…
So here is a diagram representing the design of the OOP program in which you can group together related data(fields or variables) and behaviors(methods) to form a simple template or class:
Here is how you can structure and design an OOP program or software.
Conclusion
It’s good to use the OOP concept in programming due to its several benefits and advantages. Implementing Object-Oriented Programming can save a lot of time for the programmers as programmers can break down problems in smaller reusable modules and can analyze the problems very efficiently.