Home  • Programming • Java

What is Encapsulation in java and OOP with an example?

Encapsulation Encapsulation in Java or object oriented programming language is a concept which enforce protecting variables, functions from outside of class. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. The public methods are the access points to this class' fields from the outside class. Normally, these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters. Example /* Main.java */
public class Main{
   public static void main(String args[]){
      Point2D obj1 = new Point2D(3,5);      
      System.out.print("(x,y)=(" + obj1.getX()+ ","+ obj1.getY()+")");
    }
}//end Main class

public class Point2D{

   private int x;
   private int y;
   
   Point(){
      this.x=0;
      this.y=0;
   }
   Point(int _x,int _y){
      this.x=_x;
      this.y=_y;
   }
   public int getX(){
      return this.x;
   }

   public String getY(){
      return this.y;
   } 

   public void setX()( int _x){
      this.x = _x;
   }

   public void setY(int _y){
       this.y = _y;
   }

}// end Point2D class
Advantage of Encapsulation in Java and OOP The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code. 1. Encapsulated Code is more flexible and easy to change with new requirements. 2. Encapsulation in Java makes unit testing easy. 3. Encapsulation in Java allows you to control who can access what. 4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environment. 5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing are encapsulated in one place. 6. Encapsulation allows you to change one part of code without affecting other part of code.

Comments 1


Thanks sir for your post.

Share

Copyright © 2024. Powered by Intellect Software Ltd