What is Encapsulation in Java – Best Answer

Answer includes concept of encapsulation in java oops with various java encapsulation examples with programs.

Answer:

Encapsulation in Java is one of the oops principles that is used for hiding complexities in programs.

NOTE: Many candidates answer to this interview question “What is encapsulation in java” like wrapping the class member fields into a method as a single unit”. This answer is partially correct and is not a good acceptable answer. In fact, the encapsulation definition should be just hiding the complexities in the program.

What does encapsulation mean? Simple definition of encapsulation is the process of hiding complexities in programs. So, whatever the ways we find to hide complexities or say information’s in java object oriented programming, that is known as encapsulation process.

Here are some of the ways we hide information’s. (Program examples after points)

  • Wrap class fields (data/variables) with public methods. – Using Getter and Setter
  • Hide internal methods of class using private access specifiers etc.

1) Wrapping class fields with public method:

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.

In below program, we have make the variable int a private, so, it cannot be accessible from outside of the class and have provided a public getter and setter methods to access the variable int a. So, class field int a is hidden from outside world.

class A {
	
	private int a;

	//Getter method
	public int getA() {
		return a;
	}

	//setter method
	public void setA(int a) {
		this.a = a;
	}
}

2)Hide internal methods of a class – by making them private

In below class m1() method is an internal method that is used by the class itself only and cannot be accessible outside of the class

class A {

	// Hide internal method using private access specifier
	// so it cannot be accessible from outside of the class
	private void m1() {

	}

	// public method accessible outside of the class
	public void m2() {
		// Call internal method
		m1();
	}

}

Related Posts