Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

Encapsulation in Java

Encapsulation in Java or object oriented programming language is a concept which enforces protecting variables, functions from outside of class, in order to better manage that piece of code and having least impact or no impact on other parts of a program due to change in protected code. Encapsulation in Java is visible at different places and Java language itself provide many constructs to encapsulate members. You can completely encapsulate a member be it a variable or method in Java by using private keyword and you can even achieve a lesser degree of encapsulation in Java by using other access modifiers like protected or the public. Lets see an example to understand this concept better.

class Student {

	private int id;
	private String name;
	public void setId(int id){
		this.id=id;
	}
	public void setName(String name){
		this.name=name;
	}
	public int getId(){
		return id;
	}
	public void getName(String name){
		return name;
	}
 }
 public class TestEncapsulation {
	public static void main(String[] args) {
		TestEncapsulation test=new TestEncapsulation();
		test.setId(1);
		test.setName("gps");
		System.out.println("Id ="+test.getId());
		System.out.println("Name ="+test.getName());
	}
}
 

Output :

Id = 1
Name = gps

In above example there are two data members (or data fields). both are private which cannot be accessed directly. These fields can be accessed via public methods only. Fields id, name are made hidden data fields using encapsulation technique of OOPs.

Why Is Encapsulation ?

Flexibility :

It's more flexible and easy to change the encapsulated code with new requirements. For example, if the requirement for setting the age of a person changes, we can easily update the logic in the setter method

Reusability :

Encapsulated code can be reused throughout the application or across multiple applications. For example, the Student class can be reused whenever such type of object is required.

Maintainability :

Application ode is encapsulated in separate units (classes, interfaces, methods, setters, getters, etc) so it's easy to change or update a part of the application without affecting other parts, which reduces the time of maintenance.