Encapsulation in Java

Walden Systems  Geeks Corner Encapsulation in Java programming tutorial Rutherford NJ New Jersey NYC New York North Bergen County
Java Powers the Biggest Technology. Mobile. Web apps. The Internet of Things. Big data. Machine learning. Cloud platform and cloud infrastructure. The next big things are here now, and Java is at the center of them all. Whether you’re developing the robust enterprise back end, building the agile front end, or thriving in a DevOps role, Java skills can up your game. With more than 10 million programmers and 13 billion Java-enabled devices worldwide, Java is the language that connects applications to data, data to people, and people to their digital lifestyle.

Encapsulation is one of the fundamentals of OOP concept. Encapsulation in Java is a way of wrapping the data and methods together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. To encapsulate in Java, we have to declare the variables of a class as private and provide getters and setters to modify the variables.

public class Student 
{
   private String name;
   private int age;

   public int getAge() 
   {
      return age;
   }

   public String getName() 
   {
      return name;
   }

   public void setAge( int newAge) 
   {
      age = newAge;
   }

   public void setName(String newName) 
   {
      name = newName;
   }
}

Advantages of encapsulation

Encapsulation improves maintainability and flexibility and re-usability. The methods can be changed in one place. Since the implementation is purely hidden for outside classes they would still be accessing the private field the same way. Hence the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the underlying class. The fields can be made read-only by not defining setter methods in the class or write-only by not defining the getter methods in the class) For e.g. If we have a variable that we don’t want to be changed so we simply define the variable as private and we just need to define the get method for that variable. Since the set method is not present there is no way an outside class can modify the value of that field. User don't know what is going on behind the scenes. They would only know that to update a field, they need call a set method and to read a field, call get method but what these set and get methods are doing is purely hidden from them.