Java Encapsulation Example

Objective of this section is to describe the Encapsulation and its implementation in Java program.

Java Encapsulation Example

Objective of this section is to describe the Encapsulation and its implementation in Java program.

Java Encapsulation Example

Java Encapsulation Example

In this section we will read about how to achieve the Encapsulation, feature of OOPs, in Java.

Encapsulation is one of the concept of OOPs. Encapsulation is mechanism for hiding informations. This mechanism allows to hide the internal process of data from outside of the data definition. Java provides a degree of control over hiding the data processing using the Java keywords like, public, private. Implementation of Encapsulation makes the application robust because, it can reduce the complexity of system by specifying the access of software components.

Encapsulation in Java is achieved by declaring the data members as private. It makes the data inaccessible outside the class i.e. no other code outside of the class can access these data.

Encapsulation allows the flexibility, extensibility, maintainability to our code.

In simple, concept of encapsulation can be implemented by following the Java Bean's naming convention in the class. Data members of this class should be declared as private and there should be the corresponding public setter getter method that the client code can access the data through these public methods rather than accessing them directly.

Example

Here I am giving a simple example which will demonstrate you how Encapsulation concept can be applied through programming. In this example we will create a class by following the Java Bean's naming convention. In this class we will declare the variables as private data members and then we will define the public setter and getter methods respective to the data members. Then we will create an another class for accessing the private data members outside of its class scope.

Employee.java

public class Employee {

	String empName;
	int empAge;
	int empSal;
	
	public void setEmpName(String empName)
	{
		this.empName = empName;
	}
	public String getEmpName()
	{
		return this.empName;
	}
	
	public void setEmpAge(int empAge)
	{
		this.empAge = empAge;
	}
	public int getEmpAge()
	{
		return this.empAge;
	}
	
	public void setEmpSal(int empSal)
	{
		this.empSal = empSal;
	}
	public int getEmpSal()
	{
	    return this.empSal;
	}	
}

MainClass.java

public class MainClass {
	
	public static void main(String args[])
	{
		Employee emp = new Employee();
		emp.setEmpName("James");
		emp.setEmpAge(25);
		emp.setEmpSal(50000);
		
		System.out.println("Name \t Age \t Salary");
		System.out.println(emp.getEmpName()+" \t "+emp.getEmpAge()+" \t "+emp.getEmpSal());	
	}
}

Output

When you will execute the above example you will get the output as follows :

Download Source Code