Encapsulation in Object Oriented Programming OOP

Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

The encapsulation is the process of grouping or wrapping up of data and functions to perform actions on the data into the single unit. The single unit is called a class. Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object. It keeps the data and the code safe from external interference.

The main purpose or use of the encapsulation is to provide the security to the data of a class.

To make the data secure we need to use private access modifiers that will restrict the access to the data outside the class. The access modifiers are used to define the access level or scope of the class members like data members and functions.

The Object oriented programming provides the access modifiers like

  • Private :-

    The access scope of the private members are restricted to the class scope only, means private members are not accessible or available from the another class.

  • Default :-

    It is not a keyword, if any access modifiers keyword is not defined then it will be considered as default.

    The access scope of the default members are restricted to the current or same package(folder).

    The default members are not accessible or available from classes that are not present in the same package.

  • Protected :-

    The access level or scope of the protected class members are restricted to within the current or same package and from another package if and only if a class is inherited by the class from another package.

  • Public :-

    The access modifier has widest scope mean the public class members can be accessed from any class despite package of the classes and relationship.

Example: Here we are creating a data class.

class  UserLogin
{
// private instance variables 
private String username;
private String password;
public void setName(String name)
{
username = name;
}
public String getName()
{
return username;
}
public void setPassword(String pass)
{
password = pass;
}
public String getPassword()
{
return password;
}
}