Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

object oriented
data hiding

How to use encapsulation in Java

Educative Answers Team

Encapsulation is one of the fundamental concepts of Object Oriented Programming (OOP) paradigm. It is the process of wrapping the data stored in the member variables of a class with its member functions.

It is done in such a way that the data is hidden to everything outside the class scope, and can only be accessed and modified through its own member functions.

This is normally done to hide the state and representation of a class object from outside.

svg viewer

Benefits of data hiding

  • Security: The main advantage of encapsulation is the security of your data that comes with it since it can no longer be directly accessed from outside the class.

  • Control: Encapsulation gives the developer total control over what is stored in the member variables.

  • Flexibility: Good design approaches such as encapsulation make your code flexible, which in turn makes the code easier to change and maintain.


  • An encapsulated class HiddenClass has been declared in a separate file under the same name.

    • Lines 5-7: HiddenClass has all its member variables declared as private, so now they cannot be accessed from outside the class scope.

    • Lines 11-25: Getter methods have been defined as member functions. Data can only be accessed by calling these functions.

    • Lines 29-43: Setter methods have been defined as member functions. Data can only be modified by calling these functions by passing a value as the function parameter.

  • The Test class includes the main function.

    • (Line 3): It first creates a HiddenClass object.
    • (Lines 6-8): Data is stored inside the member variables through the member functions.
    • (Lines 11-13): Data is accessed from inside the member variables and displayed on the screen.
public class Test{	 
	public static void main (String[] args){ 
		HiddenClass obj = new HiddenClass(); 
		// Setting values of member variables
		// Displaying values of member variables
		System.out.println("Name: " + obj.getName()); 
		System.out.println("Age: " + obj.getAge()); 
		System.out.println("City: " + obj.getCity()); 
		// Direct access of member variables 
		// is not possible due to encapsulation 
		// System.out.println("City: " +;
    // will give an error		 


object oriented
data hiding
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring