Java Encapsulation Sample Code

What exactly is encapsulation in terms of Java object oriented programming? If you look up encapsulation in the dictionary it defines it as to enclose or to be enclosed in or as if in a capsule. Java Encapsulation is the ability for a Java object to hide or reveal its methods and data.

A Java class encapsulates the fields and the methods, which define the actions of the object. For the Java programmer, encapsulation gives the ability to develop reusable programs.

Taking a look at the sample code below that examines Encapsulation, we have defined two classes defined. The first class called JavaEncapsulation is used to instantiate the other class called Employee. Two fields have been defined in the Employee class. The employeeId is public and employeeSSN is private. After creating a new instance of Employee, we have no problem setting the employeeId field to 1111. Attempting to set employeeSSN the same way results in the error: The field Empployee.employeeSSN is not visible. The employeeSSN field is essentially hidden because it is defined as private.



We still want to keep employeeSSN hidden, but have the need to be able to set it. How do we do that? We define a new method that is public (ie: not hidden) from the world that can be called to set employeeSSN. Encapsulation allows you to restrict or allow access to fields. If you wanted to now restrict access to employeeSSN, you can make the setEmployeeSSN private. Using set methods also allows the programmer to do some processing of the field before setting it. You can check to see if the format is correct or whether or not the field has already been set.

The table below shows the access to members permitted by each modifier. As you can see, a class always has access to its own members regardless of the modifier.

Modifier Class Package Subclass World
public Yes Yes Yes Yes
protected Yes Yes Yes No
no modifier Yes Yes No No
private Yes No No No



Java Encapsulation Sample Code:

package com.jcd.java.tutorials;


public class JavaEncapsulation 
{

	public static void main(String[] args) 
	{
		
		Employee employee = new Employee();
		employee.employeeId = 1111;
		employee.setEmployeeSSN(111111111);
	}

}
class Employee
{
	
	public int employeeId;
	private int employeeSSN;
	
	public void setEmployeeSSN(int ssn) 
	{
		this.employeeSSN = ssn;
	}
	
}

Add a Comment

Your email address will not be published. Required fields are marked *