Unlock the complete
Logicmojo experience for FREE

1 Million +

Strong Tech Community

500 +

Questions to Practice

50 +

Jobs Referrals

Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Cracking FAANG companies interviews with a few months of preparation

Learn Advanced Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Logicmojo - Updated Dec 12, 2024

What is Encapsulation

In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods.

Publicly accessible methods are generally provided in the class to access or modify the state more abstractly. In practice sometimes methods (so-called "getters" and "setters") are provided to access the values indirectly, but, although not necessarily a violation of abstract encapsulation, they are often considered a sign-post of potentially poor object-oriented programming (OOP) design practice.

The most important principle of object orientation is encapsulation: the idea that data inside the object should only be accessed through a public interface – that is, the object’s methods.

If we wish to use the data held in an object to perform an action or generate a derived value, we must define a method for the object. Then we call the method on the object anytime we wish to perform this operation. We believe that retrieving information from within an object and then writing separate code to do the action outside of the object is bad practise.

Encapsulation is a good idea for several reasons:

  1. The functionality is defined in one place and not in multiple places.

  2. It is defined in a logical place – the place where the data is kept.

  3. Data inside our object is not modified unexpectedly by external code in a completely different part of our program.

  4. When we use a method, we only need to know what result the method will produce – we don’t need to know details about the object’s internals in order to use it. We could switch to using another object which is completely different on the inside, and not have to change any code because both objects have the same interface.

"Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object...encapsulation focuses on the implementation that gives rise to this behavior"

Real-Life Example of Encapsulation:

Let's look at a real-life example to better comprehend the notion of encapsulation. Consider a Capsule as an example (Medicine). The capsule's powder is made up of many components, and the capsule's outer shield protects the internal components from the outside world. Similarly, we can wrap data and code as a single unit and secure it from outside code using Encapsulation.

Types of Encapsulation in OOPs

In Object Programming, there are three primary ways for encapsulating data. Encapsulation can be used to encapsulate data members, methods, and classes.

  1. 1. Data Member Encapsulation

    Data members can be defined as Private members of the Class. Setters and Getters methods should be used by any object that wants to change or retrieve the value of a data member.

  2. 2. Method Encapsulation

    We can hide methods used for internal implementation that does not need to be visible to the public. The method should be declared as private so that the user does not have access to it.

  3. 3. Class Encapsulation

    Our implementation might contain an internal implementation of a class that stores and processes specific information. We encapsulate that class by defining it as private and hiding it from user access. These classes should not be included in any public interface.

Implementation in C++

class employee
        int ID;
        string name;
        int joinYear;
    int getId()
        return ID;
    string getName()
        return name;
    int getYear()
        return joinYear;
    void setId(int newID)
        ID = newID
    void setName(string newName)
        name = newName
    void setYear(int newYear)
        joinYear = newYear

We’ve defined an employee class that has 3 data members: ID, name, and joinyear; and has 6 methods: getid(), getname(), getyear(), setid(), setname() and setyear().

How this code ensures encapsulation?: We bundled all details of an employee under employee class (Bundling of data). We also restricted direct access to data members by using private access specifier (Data hiding).

Implementation in Java

class Student
    private String studentName;
    private int studentRollNumber;
    private int studentAge;

    public int getAge() 
        return studentAge; 

    public String getName() 
        return studentName; 
    public int getRollNumber() 
        return studentRollNumber; 
    public void setAge(int newAge) 
        studentAge = newAge; 
    public void setName(String newName)
        studentName = newName;

    public void setRoll(int newRoll) 
        studentRollNumber = newRoll; 

How to use Encapsulation to hide Information

The encapsulation idea can be used to construct an information-hiding method, as was previously stated. This is one of the most widely utilised mechanisms in Java and is comparable to the abstraction idea. Almost all well-implemented Java classes have examples of it.
You put in place a system for information concealment by blocking outside access to the class characteristics. For attributes that you want other classes to be able to read or update, you can additionally provide getter and/or setter methods.

Access Modifiers

You can limit the scope of a class, function Object() { [native code] }, variable, method, or data member by using access modifiers. It places some limitations on class members so that external functions cannot directly access them. There are four different kinds of access modifiers in object-oriented programming:


The scope of the public access modifier is extensive. It indicates that other classes and functions may access public class members (classes, methods, or data members). In other words, there are no restrictions on the scope of public class members, and they can be accessed from anywhere in the programme.


Only the member methods inside the class are able to access the class members that have been designated private, which is only applicable to that class. In other words, no object or method outside the class can directly access them.


Comparable to a private access modifier, a protected access modifier restricts access to members of the same class or any subclasses descended from it. Depending on the modes of inheritance, this access through inheritance may change the access modifier of the base class elements in the derived class.


A class, method, or data member is said to have the default access modifier by default if no access modifier is provided for it. In other words, access for default members is restricted to the most recent or identical package. The default members cannot be accessed or used by classes outside of the same package.

Difference between Encapsulation and Abstraction?

To understand the difference, understanding abstraction is important:

Abstraction is a technique for displaying only the information that is required while hiding the rest. The basic function of abstraction, we can argue, is to hide data. Abstraction is the process of picking data from a huge set of data in order to display the information required, hence minimising programming complexity and effort.

Let's look at how they differ from one another:.

  1. Encapsulation is the process of hiding the implementation that results in an object's behaviour, whereas abstraction is the process of concentrating on an object's observable behaviour.

  2. Information can be acquired through abstraction, but it can also be contained by encapsulation.

  3. Problems are dealt with via abstraction at the interface level and by encapsulation at the implementation level.

  4. Encapsulation protects information from the outside by confining it within a single entity, whereas abstraction entails hiding undesired information.

  5. Encapsulation can be performed using access modifiers like private, protected, and public, While Abstraction can be implemented using abstract classes and interfaces.

  6. Encapsulation encourages a distinct separation of responsibilities by explicitly establishing boundaries between various abstractions.

Advantages of Encapsulation

  1. Data Protection: The program runner will not be able to identify or see which methods are present in the code. Therefore he/she doesn’t get any chance to change any specific variable or data and hinder the running of the program.

  2. Flexibility: The code which is encapsulated looks more cleaner and flexible, and can be changed as per the needs. We can change the code read-only or write-only by getter and setter methods. This also helps in debugging the code if needed.

  3. Reusability: The methods can be changed and the code is reusable.

Disadvantages of Encapsulation

  1. Code Size:The length of the code increases drastically in the case of encapsulation as we need to provide all the methods with the specifiers.

  2. More Instructions: As the size of the code increases, therefore, you need to provide additional instructions for every method.

  3. Increased code execution: Encapsulation results in an increase in the duration of the program execution. It is because more instructions are added to the code therefore they require more time to execute.

With this article at Logicmojo, you must have the complete idea of encapsulation in oops

Frequently Asked Questions (FAQs)

Along with inheritance, polymorphism, and abstraction, encapsulation is one of the four essential principles of Object-Oriented Programming (OOP). Object-Oriented Programming (OOP) is a style of computer programming. Data and the methods that operate on these data are combined into a single entity that is referred to as an object.

This process is referred to as "bundling." Encapsulation is a technique that ensures the data's authenticity and protection by surrounding it in a barrier that prevents it from being accessed directly by unauthorized parties.

Key Takeaways:

• Data and procedures can be encapsulated when they are combined into a single entity known as an object.

• It is a fundamental notion of OOP that ensures the integrity of the data as well as its safety.

• By preventing direct access to data, encapsulation ensures that interactions are managed in a controlled manner via methods.

encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods.

For Example

Of course, let's give a practical illustration to help you comprehend the idea of encapsulation. Think about a coffee maker. It's a complicated machine with several internal parts, including a coffee bean grinder, a water heater, and a pump. To make a cup of coffee, each of these elements works together in a precise way.

Do you, as a consumer, need to comprehend how all of these components work together to brew coffee? No. You simply need to interact with the machine's offered buttons or interface. The machine starts when you click a button, and after you might change the coffee's strength, it takes care of the rest.

The coffee maker in this case is an illustration of encapsulation. The user is not aware of the internal processes that heat the water, grind the coffee beans, pump the water, etc. Only the buttons, a constrained and restricted interface, allow the user to interact with the system. The user isn't even aware that anything is amiss inside the machine unless it stops it from brewing coffee.

The machine takes care of all the technical details; the user doesn't have to worry about how the water is heated to the proper temperature, how the beans are ground, or how the water is pushed through the system. The coffee maker encapsulates its internal data (the state of its components) and the methods that operate on it (the actions to make coffee), much like a class in OOP. The basic principle of encapsulation is demonstrated in this example, which involves grouping related data and behaviors into objects and making a straightforward interface available to other users.

Encapsulation is the process of hiding complicated features and giving an easy-to-use, secure interface, whether in real life or in programming.

• Promotes Modularity and Code Reusability: Encapsulation makes it easier to combine similar characteristics (data) and methods into an object. The grouping improves the organization of the code and makes it more modular. A program's modules are simpler to comprehend, control, and debug. Additionally, when the code is organized in this manner, it becomes very reuseable. You can build an instance of the object, or in other words, an object based on the class blueprint, and utilize it wherever necessary rather than having to rewrite the same code. As a result, development is more productive and code redundancy is decreased.

• Maintains Object State Privately: The fact that an object's characteristics (or state) are kept secret is one of the fundamental principles of encapsulation. They cannot, therefore, be directly accessed from outside the object. Instead, interaction with these private attributes is supported by public methods (sometimes referred to as getter and setter methods). This makes it simpler to maintain and update because the object is able to manage its own state. A change in an object's state, for example, can be controlled within the object itself without having an impact on other program elements.

• Provides Control Over Data Access and Manipulation: Encapsulation makes guarantee that an object's data may only be accessed or changed by using the object's methods. The integrity of the data must be maintained at this level of control. For example, it might restrict the speed property of a car from being adjusted to a negative value. Encapsulation helps avoid unforeseen consequences that could arise from improper or erroneous modification of an object's characteristics by offering this control.

Encapsulation in OOP essentially assures a clear, well-structured, and reliable code base. Encapsulation improves the overall structure and security of the software by hiding the intricate features of an item and offering other sections of the program a straightforward and secure interface to deal with.

In object-oriented programming (OOP), encapsulation is a concept that is realized by making use of the structure that classes offer. Let's examine this procedure in more detail and learn how it works.

Important information:

Implemented Using Classes: A class in OOP functions as a blueprint or template for building objects. It gives guidelines for how an object should be made, including what kind of information it will store (known as attributes or properties) and the actions it can carry out (known as methods or functions). Encapsulation refers to the process of organising and packaging components within a class. The relevant data and operations are encapsulated or wrapped up by the class into a single, cohesive object.

Private Data: Maintaining the privacy of a class's data or properties is one of the main goals of encapsulation. This indicates that users outside of the class cannot directly access the data. In order to keep the data's integrity, this helps stop unwanted access or adjustments. Interaction with the data is possible through public methods supplied by the class rather than by directly altering the data.

Accessible through Methods: A class may include private data, but it may also contain public methods (often referred to as getters and setters) that allow access to or modification of that data. These procedures create an interface that allows other sections of the program to communicate with the object. The object can regulate and verify any alterations to its data thanks to this system. Think of a class that represents a bank account as an illustration. It might have a technique for withdrawing money that verifies there are enough funds in the account before conducting the transaction. This preserves the data's integrity (the account balance can never be negative) and incorporates the reasoning behind money withdrawals within the account class.

In conclusion, OOP's encapsulation protects and hides data within classes while allowing for restricted access and modification through public methods. As a result, a solid structure is created that protects data integrity and lowers the likelihood of unwanted changes.

A Bank Account class in a banking application can be used as a real-life example of encapsulation in the programming world. Think of a straightforward "BankAccount" class that symbolizes a client's bank account. Such private characteristics (data) as accountNumber, accountHolderName, and balance may be present in the class. To avoid unwanted access and to protect the data's integrity, some properties are kept secret. We wouldn't want the balance characteristic, for instance, to be immediately available because that could result in deceptive manipulations. Since they include sensitive information, the accountNumber and accountHolderName are likewise kept confidential.

public class BankAccount {
   private String accountNumber;
   private String accountHolderName;
   private double balance;

   // Constructor, getters, and setters not shown

Public ways to interact with these private characteristics are provided by the BankAccount class. For instance, it might have functions like checkBalance(), withdraw(), and deposit(). These techniques guarantee that interactions with the attributes adhere to predefined guidelines. For instance, before lowering the balance, the withdraw() method can first determine if the withdrawal amount is lower than or equal to the current balance.

The data (attributes) are thus contained within the BankAccount class, which also offers restricted access and manipulation via methods. Users of the class, who communicate with the object (a class instance), are not aware of the specifics of how the data is kept or how the methods operate. Encapsulation in action, it's essential for preserving the security and integrity of the data.

Abstraction within OOP

In Object-Oriented Programming (OOP), the fundamental principle of abstraction deals with the idea of simplifying complex systems by modeling them in a way that emphasizes the key traits that are crucial for solving the problem at hand, while suppressing or ignoring their other, less crucial details or complexities.

Programmers can concentrate on the "what" while putting the "how" out of their minds thanks to abstraction. For instance, a car's color, brand, speed, and other attributes can be used to characterize it. The internal workings of the car, such as how the engine and brakes work, are abstracted away.

In OOP, interfaces and abstract classes (in languages that support them, like Java) are largely used to achieve abstraction. The 'what' of the semantic contract is defined by an interface, including the methods that can be called, the parameters required, the kind of output that is produced, etc. The 'how' is not provided, though; the classes that implement the interface are responsible for carrying out the actual implementation.

Encapsulation within OOP

The idea of grouping related data and operations that act on that data into a single unit, commonly known as an object, is referred to as encapsulation, another important OOP principle.

Encapsulation is the process of exposing only what is necessary and concealing the interior workings of an object. By limiting direct access to an object's attributes, it safeguards the object's internal state and preserves data integrity. Instead, methods (getters and setters) are used to access the attributes. These methods frequently incorporate validation or other constraints to safeguard the data against improper change.

Encapsulation, which decreases complexity and boosts security, essentially produces a "black box" or a protective shell around an object's data and actions.

The connection between encapsulation and abstraction

Although they are both essential to OOP, abstraction and encapsulation deal with separate facets of program design. By concentrating on important aspects and obscuring non-essential details, abstraction aims to reduce the complexity of complex systems. Encapsulation, on the other hand, protects the confidentiality and integrity of data by concealing an object's internal operations and presenting a constrained and managed interface for external interaction.

The two ideas go hand in hand while designing software. While encapsulation makes sure that the implementation of these behaviors is concealed and shielded from unauthorized access and manipulation, abstraction enables us to specify the necessary qualities and actions in a straightforward manner. By doing this, they contribute to a codebase that is organized and modular, making it simpler to create, maintain, and comprehend.

There aren't really "three types" of encapsulation in Object-Oriented Programming (OOP), per se. However, there are three distinct viewpoints or levels of access control for class members, which are commonly specified using access modifiers. Access modifiers can vary amongst computer languages, but the three most frequent ones are public, private, and protected.

Public Encapsulation:

A class member can be accessible from anywhere in the code, including from outside the class or the package where the class is created, if the member is designated as public. This offers the maximum level of accessibility at the expense of the least amount of data protection. While declaring data members (attributes) as public is frequently important for interacting with an object, doing so runs the risk of exposing the object's internal state without any checks or validation.

Private Encapsulation:

A class member can only be accessible from within the class itself if it is designated as private. This assures that the member cannot be directly accessed or modified from outside the class, offering the highest level of data protection. Instead, public getter and setter methods—which may include any necessary validation or control logic—typically allow access to secret members.

Protected Encapsulation:

If a class member is marked as protected, it is possible to access that member only within that class, its subclasses (i.e., classes that inherit from that class), and, depending on the language, possibly even within the same package. By providing greater accessibility than private while maintaining some amount of data protection, this offers a compromise between the two.

These access levels each make a unique contribution to the idea of encapsulation. Public encapsulation helps by giving an interface that other classes can use to communicate with the object, whereas private and protected aid to safeguard an object's internal data. Effective encapsulation implementation in OOP depends on the proper usage of these access modifiers.

Encapsulation, Inheritance, Polymorphism, and Abstraction are the four major tenets or "pillars" of Object-Oriented Programming (OOP). Let's examine each one in greater detail:


This is the idea behind grouping together related data and functions that manipulate that data into a single entity known as an object. In order to safeguard the data and retain its integrity, it also entails hiding the internal state of these objects and offering a straightforward interface for object interaction. Encapsulation makes the code more manageable and safe while ensuring that the data cannot be altered maliciously or unintentionally.


The ability of a new class to take on the attributes and functions of an existing class is known as inheritance. It encourages code reuse and the development of hierarchical relationships between classes. The class that inherits these properties is known as the subclass, and the class from which they are inherited is known as the superclass. The creation of hierarchies is made possible by inheritance, which also helps to clean up redundant code and improve consistency.


"Many forms" is what the word "polymorphism" signifies. Polymorphism in OOP enables objects of many classes to be considered as belonging to a single superclass. This suggests that, depending on the object being operated upon, a single method or function might have various implementations and behaviors. As several object types may be handled using the same interface and new object types can be added without altering current code, it encourages flexibility and extensibility.


The idea behind abstraction is to make complicated systems simpler by just showing the user the aspects that are absolutely necessary while hiding the more intricate internal workings. By using abstract classes or interfaces, this is accomplished. Abstraction's goal is to manage larger systems by lowering complexity by breaking down complex activities into simpler ones and obscuring implementation specifics.

Through the encouragement of reusability, flexibility, security, and manageability in code design, each of these concepts offers a method for managing complexity in programming. They are widely utilized in software development and serve as the cornerstone of efficient OOP design.

OOP relies on encapsulation and polymorphism. They're similar yet serve different objectives. Before discussing polymorphism, let's grasp encapsulation.

Encapsulation: Object-oriented programming encapsulates data and methods (functions) into a single object. It conceals an object's inner workings. Encapsulation controls and secures data access and manipulation in objects.

Encapsulation protects an object's private data members, which represent its internal state. Instead, public methods—accessors and mutators or getters and setters—interact with the object's internal state. These methods allow access, modification, and manipulation of the object's data.

Encapsulation benefits:

1. Data Hiding:Encapsulation hides data from outside the object by making its internal state private. This restricts data access to the object's declared methods, giving more control over data manipulation.

2. Data Integrity: Encapsulation lets methods validate and limit object data. This maintains data integrity during the object's lifespan.

3. Code Modularity: Encapsulating related data and activity into one entity encourages modular architecture. As black boxes with well-defined interfaces, objects are easier to understand, manage, and modify.

However, polymorphism allows objects of different kinds to be considered as instances of a single superclass. It lets items have distinct behaviors or shapes while sharing an interface.

Inheritance and overriding create polymorphism. A class can inherit a superclass's methods and override them. If they follow the common interface, derived class objects can be used interchangeably with superclass objects.

Encapsulation allows polymorphism. Encapsulation gives objects structure and modularity to implement polymorphic behavior.

Encapsulated objects have defined interfaces (methods) and hide their internal state. These methods are objects' common interface. This common interface allows items to be utilized polymorphically in code that expects them.

Encapsulation hides object internals and controls access through well-defined interfaces, enabling polymorphism. Encapsulation allows polymorphism to handle objects of different kinds interchangeably if they have a common interface. These approaches improve object-oriented programming code organization, modularity, and flexibility.

Abstraction and encapsulation are two important concepts in object-oriented programming (OOP), but they deal with different facets of software architecture and complexity management. How they differ is as follows:


1. The process of abstraction involves hiding the technical specifics and merely displaying the functionality to the users. In other words, it concerns with how an object (interface) seems from the outside.

2. Abstraction is primarily used to manage complexity by hiding unrelated details from the user. Programmers can achieve this by developing abstract classes or interfaces.

3. Abstraction enables the programmer to concentrate on the function of an object rather than its implementation.

4. Java uses abstract classes and interfaces to implement abstraction.


1. Encapsulation is the process of combining code and data into one cohesive entity, similar to a capsule, which is an OOP class.

2. The basic goal of encapsulation is to prevent unauthorized access to and change of an object's internal state.

3. Encapsulation enables the programmer to restrict the data access and modification capabilities of an object.

4. Getters and setters methods in classes, as well as access modifiers like public, private, and protected, are used to provide encapsulation.

There are various benefits to encapsulation in object-oriented programming. These are encapsulation's main advantages:

1. Data concealment:

Encapsulation enables you to conceal an object's internal workings and shield its data from direct access by outside code. You can manage who has access to and how the data is changed by keeping data members private. This stops unintentional changes and guarantees that only specific techniques can be used to edit data. Data concealment protects the state integrity of the object and improves security.

2. Modularity and Maintainability:

By combining related data and activity into a single unit, the object, encapsulation encourages modularity. Code is simpler to comprehend, maintain, and adapt because to this modular design. Encapsulation allows for the treatment of objects as well-defined interface-only black boxes. As long as the interface is consistent, any modifications or upgrades to an object's internal implementation can be made without having an impact on the external code that utilizes it. Encapsulation aids in the separation of implementation-specific details, lowering dependencies and facilitating more adaptable code organization.

3. Reusability and Flexibility of the Code:

You can define public methods or interfaces that provide for controlled access to an object's internal state via encapsulation. As long as the object's public interface doesn't change, this abstraction enables you to modify the object's internal implementation without affecting the code that utilizes it. With this flexibility, you can improve or streamline an object's implementation while still keeping old code compatible. Encapsulated objects also offer a clearly defined interface for interaction, making it simple to reuse them in many settings.

4. Data Integrity and Validation:

You can impose limitations and validation criteria on the data of the object within its methods thanks to encapsulation. Data consistency and validity can be guaranteed throughout the lifetime of the object by encapsulating data and behavior together. Before changing the data, the encapsulated methods can carry out checks and validations, preventing inaccurate or inconsistent states. This enhances the system's overall reliability and aids in the maintenance of data integrity.

5. Encapsulation Promotes Polymorphism

In order to achieve polymorphism, encapsulation is essential. Encapsulation offers the necessary structure and modularity to provide polymorphic behavior by enclosing relevant data and action into objects. Different sorts of objects can abide by a common interface, enabling them to be used interchangeably. By encouraging code flexibility and extension, more modular and flexible systems can be created.

Encapsulation has a lot of advantages, but it could also have some disadvantages. A few disadvantages of encapsulation are as follows:

1. Performance Overhead and Indirect Access:

The internal data of an object cannot be accessed directly due to encapsulation. Access is instead made available through open channels or interfaces. Compared to direct access, this indirect approach may result in performance overhead. The extra overhead of method resolution, argument passing, and potential method execution comes with each method call. The overhead of encapsulation could be problematic in instances when performance is crucial.

2. Growing Complexity

Code design and implementation may get more difficult as a result of encapsulation. The codebase can become more organized and modular by encapsulating data and functionality within objects. However, this could also add more indirection and abstraction levels, complicating the code. It may take more time and careful planning to comprehend and maintain the interactions and links between contained things.

3. Lack of Visibility:

The visibility of internal data and implementation details may be limited through encapsulation. The ability to view and alter an object's internal state from the outside may be constrained, despite the fact that doing so is frequently desirable for data hiding and preserving encapsulation. In some debugging or testing contexts, where direct access to internal state would be advantageous, this can be a problem. Although controlled access can be provided through methods like getters and setters, they do not always offer the same degree of flexibility as direct access.

4. Growing Code Size

Due to the addition of getter and setter methods for updating and retrieving encapsulated data, encapsulation might result in larger code. This enhances data hiding and encapsulation, but it can also lead to a larger codebase with more method declarations. This may have an impact on the readability and upkeep of the code, particularly if the class contains numerous data members that call for accessors and mutators.

5. Design That Is Too Rigid:

Excessive encapsulation occasionally leads to a stiff design that is difficult to expand upon or adjust. When encapsulation is used excessively, an object's behavior cannot be extended or changed since every aspect of the object may be contained. To make sure that the design can still be modified to meet changing needs and requirements in the future, it is essential to strike a balance between encapsulation and flexibility.

A key idea in object-oriented programming (OOP) is polymorphism, which enables objects of various kinds to be considered as instances of a single superclass. It allows objects to display various behaviors or take on various forms while still using a single interface.

Polymorphism in OOP is accomplished by method overriding and inheritance. A class can provide its own implementation of the methods it inherits from a superclass, as well as the methods from the superclass itself. As long as they adhere to the shared interface established by the superclass, objects of the derived class and objects of the superclass can be utilized interchangeably.

Compile-time polymorphism, also known as method overloading, and run-time polymorphism, also known as method overriding, are the two ways that polymorphism can be understood.

Polymorphism at Compile Time (Method Overloading)

When numerous methods with the same name but distinct argument lists are defined in a class, compile-time polymorphism happens. Based on the quantity, nature, and ordering of the arguments given during method invocation, the compiler chooses which method to call. Method overloading improves code readability and offers flexibility in handling various sorts of data by allowing a single class to have numerous methods with the same name but different behaviour.

Runtime polymorphism (overriding a method)

When a subclass offers its own implementation of a method specified in its superclass, runtime polymorphism takes place. The name, return type, and parameters of the method in the subclass must match those of the method in the superclass. The proper method implementation is chosen at runtime (dynamic binding) based on the actual type of the object being referenced to. This enables polymorphic treatment of objects of various types, allowing for flexibility and extensibility in code design.

In Python object-oriented programming (OOP), encapsulation is the process of grouping data and methods into an encapsulated object. It is a technique for planning and regulating access to an object's internal state. Encapsulation is mostly accomplished in Python through access modifiers and properties.

Unlike several other programming languages, Python does not offer stringent access modifiers like public, private, or protected keywords. To achieve encapsulation, however, there are a few conventions and techniques that can be used:

Private Attributes:

As a matter of convention, private attributes in Python are prefixed with a double underscore (__). For instance, self.__attribute designates a private class attribute. The attribute should not be directly accessed from outside the class, as indicated by the name convention, which is communicated to other developers.

Getters and Setters:

Getter and setter methods can be created within the class to give controlled access to secret attributes. These techniques make it possible for external code to access or change the value of a private attribute. Whenever additional logic or validation is required, you can do it by encapsulating attribute access within methods.


A more Pythonic technique to encapsulate attribute access in Python is through properties. To declare a method as a getter, use the @property decorator and the @attribute_name>.To designate a method as a setter, use a setter decorator. While the getter and setter methods take care of the encapsulation, attributes can be accessed and modified through properties just like standard class attributes.

In Python, encapsulation tries to facilitate data hiding and promote controlled access to characteristics. Python, on the other hand, adheres to the notion that "we're all consenting adults here," which means that encapsulation is not strictly enforced. Developers can still directly access private properties if they so desire, but generally speaking, it is best practice to follow encapsulation principles.

Logicmojo Learning Library