Encapsulation in Java

Filed Under: Java
Encapsulation In Java

What is Encapsulation?

  • Encapsulation is one of the ways to achieve abstraction in Object-oriented programming.
  • It’s one of the core concepts of OOPS paradigm.
  • Encapsulation is the process of hiding Objects’ properties from the outer world and provides methods to access them.
  • It’s the mechanism to bind together the data and the function that work on it.
  • Encapsulation hides the objects’ data, so it’s also called data-hiding.

Encapsulation in Java

We can achieve encapsulation in Java by declaring all the class fields as private. Then provide the public getter and setter methods for them.

Here is a simple example of encapsulation in a Java class.


package com.journaldev.oops.encapsulation;

public class Data {

	private int id;
	private String value;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

}

Advantages of Encapsulation

  1. The encapsulated code is loosely coupled. We can change the class variable name without affecting the client programs.
    
    private String name;
    
    public String getValue() {
    	return name;
    }
    
    public void setValue(String value) {
    	this.name = value;
    }
    

    Yes, you can’t change the methods because it might break the client code. The best way would be to mark these methods as deprecated and provide the new getter-setter methods.

    
    private String name;
    
    @Deprecated
    public String getValue() {
    	return getName();
    }
    
    @Deprecated
    public void setValue(String value) {
    	this.setName(value);
    }
    
    public String getName() {
    	return name;
    }
    
    public void setName(String name) {
    	this.name = name;
    }
    
  2. The caller doesn’t know what is happening inside the getter and setter methods. It makes our code more secure. We can add some validations in the getter-setter methods.
    
    public void setId(int id) {
    	if (id < 0)
    		throw new IllegalArgumentException("id can't be negative.");
    	this.id = id;
    }
    
  3. We can easily implement access control for the object properties. If you don't want some class variable to be set from outside, don't provide the setter method.
  4. The encapsulation helps in writing unit test cases easily. The unit testing frameworks provides ways to write test cases for the methods, not for the fields.
  5. The encapsulated code is reusable. If you didn't noticed, the above deprecated functions are using the new getter-setter methods.

References

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages