Encapsulation in Java – OOPS Concepts

In this post we’ll see the usage of OOPS concept Encapsulation in Java.

What is encapsulation

Encapsulation is one of the four fundamental principles of Object Oriented Programming along with inheritance, polymorphism and abstraction.
Encapsulation is the process of keeping the data and the code that manipulates that data together as a unit. That way data is protected from any intentional or accidental modification by any outside entity. Since encapsulation is more about protecting data from being accessed by other classes so encapsulation is also referred as data hiding.

Encapsulation in Java

Encapsulation in Java is achieved through a Java class and the access modifiers. A properly encapsulated class shall have all its fields marked as private (so can’t be accessed by any other class) and the methods with in that class defining how data can be used and accessed.

encapsulation in Java

Java example for encapsulation

Consider a Java class Voter with name, age and address fields.

public class Voter {
	private String name;
	private int age;
	private String address;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		if(age > 18)
			throw new IllegalArgumentException("Age can't be less than 18");
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	public String printSlip() {
		StringBuilder sb = new StringBuilder();
		sb.append("Name- ").append(getName()).append("\n");
		sb.append("Address- ").append(getAddress()).append("\n");
		sb.append("Age- ").append(getAge());
		return sb.toString();
	}
}

If you notice setAge() method has a condition that age should not be less than 18, if it is then exception is thrown. Consider the scenario where data fields are not marked as private, from any class following code could be written (accidentally or intentionally)

Voter voter = new Voter();
voter.age = 5;

making a 5 year old eligible to vote.

But Voter class follows encapsulation so data is only accessed through the methods of the class (setters and getters) where the required verification is done. With that any such attempt will not be successful and exception will be thrown.

Voter voter = new Voter();
voter.setAge(5);

Exception in thread "main" java.lang.IllegalArgumentException: Age can't be less than 18
	at com.knpcode.Voter.setAge(Voter.java:18)

Only when the values are proper, a voter slip can be printed.

Voter voter = new Voter();
voter.setName("Jack Reacher");
voter.setAge(25);
voter.setAddress("Pittsburgh, Pennsylvania");
System.out.println(voter.printSlip());

Output

Name- Jack Reacher
Address- Pittsburgh, Pennsylvania
Age- 25

Advantages of encapsulation in Java

  1. Since data and the code that works on that data is kept in the same Java class so encapsulation also makes the code more manageable and easy to maintain.
  2. In Java encapsulation is achieved by restricting access to the class fields that enhances security.
  3. Encapsulation also gives you flexibility about the access of the fields by making them read only, write only or both. In the example Voter class we can remove the getter methods making all the fields write only. In that case fields can only be read by using printSlip() method.

Related Posts

That’s all for the topic Encapsulation in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.