Define Encapsulation with example

Example 1: encapsulation in python

# convention: _<name> for protected and __<name> for private
class MyClass: 
    def __init__(self): 
          
        # Protected
        # No access outside of the class or subclasses
        self._this_is_protected = True
        # Private 
        # No access outside of the class
        self.__this_is_private = True

# Note:
# Private and protected members can be accessed outside of the class using python name mangling.

Example 2: Encapsulation

In object-oriented programming, 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

Tags:

Java Example