Friday, January 8, 2021

Encapsulation in Java

Encapsulation is one of the four fundamental OOP concepts. The other three are- Inheritance, Polymorphism, Abstraction


What is Encapsulation

The concept of Encapsulation is to keep together the implementation (code) and the data it manipulates (variables). Having proper encapsulation ensures that the code and data both are safe from misuse by outside entity.

Encapsulation also helps in maintaining code as the implementation that may change and evolve is kept at one place which makes it easy to change with out impacting other classes in application.

Encapsulation in Java

Foundation of encapsulation in Java is a Java class which encapsulates both methods and instance variables. Since it’s the code in the method that operates on the variables, in a properly encapsulated Java class, method should define how member variables can be used. That access control to the methods and the variables is achieved through access modifiers (public, private, default & protected).

Each method or variable in the class may be marked public or private in order to ensure access control.

  • A method or variable marked as public is accessible to other classes.
  • A method or variable marked as private is internal to the class.

In a properly encapsulated Java class you mark only those methods as public that should be accessed by the other classes. Complete encapsulation in java is achieved by making variables of a class private and access to them, outside the class, is provided only through public methods with in the same class. Any method having logic that is specific only to that class and used only by other methods of that class should be marked private.

Since the private members (variables or methods) of a class may only be accessed with in the class, no improper outside access is possible.

Following image shows the concept of encapsulation. Fields and methods are encapsulated with in the class and the methods of the class can access and manipulate fields. Outside entity can't access fields directly but need to call methods which in turn can access data.

Encapsulation in Java

Encapsulation Java Example

Lets assume there is a class Employee with its fields marked as private so that they cannot be accessed directly from outside the class. You can only access and modify values of these fields through the methods of the class. There are getter and setter methods in the class where getter methods are used for retrieving the values of the fields and setter methods are used to update values of the fields.

Let’s assume for age you have the logic that the employee can not be less than 18 years old that logic can be written in setAge() method.

Employee Bean Class

public class EmployeeBean {
	private String lastName;
	private String firstName;
	private String empId;
	private int age;
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getEmpId() {
		return empId;
	}
	public void setEmpId(String empId) {
		this.empId = empId;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		if(age >= 18) {
			this.age = age;
		}
        // throw exception if condition fails 
	}
	@Override
	public String toString() {
		
		return getFirstName() + " " + getLastName() + " " + getAge() + " " + getEmpId();
	}
}
public class EmployeeTest {
  public static void main(String[] args) {
    EmployeeBean employeeBean = new EmployeeBean();
    employeeBean.setEmpId("E001");
    employeeBean.setLastName("Mishra");
    employeeBean.setFirstName("Pyaremohan");
    // not possible to do this as field is private
    //employeeBean.age(7);
    employeeBean.setAge(35);
    System.out.println("Added Employee- " + employeeBean);
  }
}

Output

Added Employee- Pyaremohan Mishra 35 E001

As you can see trying to access age field directly employeeBean.age(7); is not possible as the field is private. It can only be accessed through methods of the class so it is not possible to pass any invalid value.

Encapsulate what varies

Encapsulate what varies is one of the design principle centered around the concept of encapsulation. By encapsulating method and fields that are required for that class you also get the advantage of making it easy to maintain and evolve your code.

As an example consider the scenario where you have to calculate tax by using the prevailing tax rate (which may keep on changing). What is the best design strategy for such scenario-
Hard coding the tax rate wherever it is used or having a single method with a access to taxRate field with in a class?

Of course by having a single method calculateTax(person) and all the other classes accessing this method is better as any change in the logic requires change just in the encapsulated method calculateTax() making it easy to maintain.

Benefits of Encapsulation

  • Encapsulation helps to maintain code that is changed frequently by keeping that in one place thus providing maintainability and flexibility.
  • Encapsulation allows you to control the access to the class.

Points to note-

  • Encapsulation is one of the four fundamental OOPS concept. Other being, inheritance, polymorphism and abstraction.
  • Encapsulation means keeping code and data together in a class.
  • An encapsulated class will have private instance variable and only the methods within that class can access those variables.
  • Outside classes will be given access to any particular class through one or more public methods only.
  • Encapsulation in Java is achieved through the access modifiers- public, private, protected and default.

That's all for this topic Encapsulation in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Difference Between Encapsulation And Abstraction in Java
  2. Method Overriding in Java
  3. Java Variable Types With Examples
  4. Object Creation Using new Operator in Java
  5. Java OOP Interview Questions And Answers

You may also like-

  1. Why main Method static in Java
  2. What are JVM, JRE and JDK in Java
  3. Constructor in Java
  4. finally Block in Java Exception Handling
  5. Exception Propagation in Java Exception Handling
  6. String in Java Tutorial
  7. Lambda Expressions in Java 8
  8. Difference Between sleep and wait in Java Multi-Threading

No comments:

Post a Comment