Encapsulation in Java

This tutorial will help you to explain about Encapsulation in Java.

Encapsulation in Java

This tutorial will help you to explain about Encapsulation in Java.

Encapsulation in Java

Encapsulation in Java

Encapsulation is one of the important feature of object oriented programming language. Wrapping of data and function together in to a single unit is called Encapsulation. It means hiding the data and function from the  outside world. Encapsulation can be achieved by making the member or function  private.  Encapsulation is the way of making the field private and accessing them by the public method.  Encapsulation make sure that the data is hidden from the outside world and accessing the data is controlled by the interface. Encapsulation permits to modify our code without breaking our code who use our code. Encapsulation gives maintainability, flexibility and extensibility of code. Encapsulation is also known as data hiding.

Encapsulation combine data and function together in a single entity.

  • Advantage of encapsulation is using object is that object need not break its field and behavior.
  • Encapsulation defined both data and function.
  • In a object oriented design, an object should only  disclose the interfaces that other object must interact with it.

Primary importance of Object oriented design is encapsulating the data and function.

 Advantage of Encapsulation is as follows :

  • Encapsulation provides maintainability of code.
  • Encapsulation provide flexibility of code and easy to change according to the new requirements.
  • Encapsulation provides extensibility of code.
  • Encapsulation make testing easy.
Let us look an example to understand encapsulation
class student 
{ 
 private int age;
 private String name;
 private String address;
  //We cannot make constructor public here because it break rule for encapsulation
 private student(int age, String name, String address)
  {
   this.age=age;
   this.name=name;
   this.address=address;
   }
   

In this example, all variable are made  private so, they all are encapsulated well you can only change or access within this class. If you want to use this field outside the class you have to use getter and setter to access these field.

Example : Code to show encapsulation in java

class ProgramDemo {
	private String Address;
	private String name;

	public String getAddress() {
		return Address;
	}

	public void setAddress(String Address) {
		this.Address = Address;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
public class Encapsulation extends ProgramDemo {
	public static void main(String args[]) {
		Encapsulation e = new Encapsulation();
		e.setAddress("New Delhi");
		System.out.println("Address = " + e.getAddress());

		e.setName("Rose India");
		System.out.println("Name = " + e.getName());

	}
}

When you compile and run the program output will look like as follows :

Download Source Code