Tutorials Hut

Java Encapsulation

Encapsulation means hiding something in terms of OOP concept. In java if we hide some variable from outside class then it will be called encapsulation.

In plain words capsules are used to hide drugs(medicine) so we don’t feel bad while taking to cure any disease, not exactly but similarly encapsulation hides some variables in class.

Encapsulation in Java

In java we can achieve encapsulation in class by hiding variables from outside word, we can do this by making variable private and then exposing it to the world by getter and setter methods.

Java Encapsulation
Encapsulation (tutorialshut.com)

Java Encapsulation Example

Below example Clock class has variable time which is private and only accessible by getter and setter methods, this is a simple example of encapsulation in java. DemoClock class is showing how to use it.
public class Clock {

	//hidden variable from outside class

	private String time;

	public String getTime() {

    	return time;


	public void setTime(String time) {

    	this.time = time;



class DemoClock {

	public static void main(String[] args) {

    	Clock clock = new Clock();


    	String time = clock.getTime();

    	System.out.println("My encapsulated time is: "+time);



My encapsulated time is: 20:00

Pojo or Bean Class In Java

In java to save any information we create bean or pojo classes, these classes are good example of encapsulation where all variables may will be private and only way to update or access is getter and setter methods for variables in pojo or bean class.

In above example of Clock class will be called a bean or pojo class as well. Check below another example of encapsulation and pojo class:


class Alien {

	private String ageOfAlient;

	private String descriptionOfAlien;

	private String nameOfAlien;

	public String getNameOfAlien() {

    	return nameOfAlien;


	public void setNameOfAlien(String nameOfAlien) {

    	this.nameOfAlien = nameOfAlien;


	public String getAgeOfAlient() {

    	return ageOfAlient;


	public void setAgeOfAlient(String ageOfAlient) {

    	this.ageOfAlient = ageOfAlient;


	public String getDescriptionOfAlien() {

    	return descriptionOfAlien;


	public void setDescriptionOfAlien(String descriptionOfAlien) {

    	this.descriptionOfAlien = descriptionOfAlien;




Article from oracle.com on oops concepts: OOP

Next Article

  • Leave a Reply

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