Loading

Encapsulation

It means wrapping up data and code together in a single unit to enhance the program's security.

Example: capsule(Tablet)

					    Encapsulation = Data Hiding + Abstraction

Key Points :

  • To create a fully encapsulated class we just to make the data of all members of the class private.
  • It provides a method to achieve data hiding.
  • Here Getter and Setter method is used to access the data from the class.
  • Getter and Setter methods give access to read and write only.
  • This method provides control over setting the values and also we write our logic inside the setter method.
  • We can also skip this getter and setter method.
  • Encapsulated class is better for testing purposes.
  • Some IDEs provide built-getter and setter methods creator shortcuts that create a fast and easy encapsulated class.

Example:

package quipoHouse;
class EncapsulationEx 
{ 
 public static void main(String[] args) 
 { 
    User obj = new User();             // Creating object of user class.
     obj.setName("QUIPO");             // Setting the values.
    String userName = obj.getName();   // Reading the value. 
    System.out.println(userName);      // Printing the values.
  } 
}
package quipoHouse;
public class User
{ 
private String name;                   // Private variable

public String getName()                // Getter method
{ 
   return name; 
} 
public void setName(String userName)   // Setter method
{ 
  name = userName; 
 } 
}

Output:

QUIPO