Encapsulation in Java

Encapsulation in Java

Posted in : Core Java Posted on : January 4, 2015 at 5:47 PM Comments : [ 0 ]

Encapsulation is an important OOPs principal which enables to write code which contains the data and implementation together in one unit. Its the self contain unit which hides the implementation from outside world.

Video Tutorial - Encapsulation in Java with example program

This video tutorial explains the encapsulation concept of the Java Programming Language. There are four important concepts of OOPs; Inheritance, Encapsulation, Polymorphism and Abstraction. The encapsulation is all about hiding the implementation and protecting the data from accidental modification.

In the encapsulation the variables are marked private and only accessed trough the public methods. To make a method un- accessible from outside we can make it private.


private double calculateCurrentBankBalance(){...}

The above declaration of the method makes it private and it can't be accessed from the object of the class. You can only access this method in the class.

Here is the video tutorial of Encapsulation in Java with example program:

Here is an example program of encapsulation in Java:

/* http://www.devmanuals.com/ */
public class BankAccount
	private String accounNumber;
	private String accountHolderName;
	private double currentBalance;

	public void setBalance(double balance){

	public double getBalance(){
		return currentBalance;

	public void setAccountNumber(String accounNumber){
	public String getAccountNumber(){
		return accounNumber;

	public void setAccountHolderName(String accountHolderName){
	public String getAccountHolderName(){
		return accountHolderName;

	public static void main(String[] args) 
		BankAccount obj = new BankAccount();
		obj.setAccountHolderName("Deepak Kumar");

		System.out.println("Acount Number: " + obj.getAccountNumber());
		System.out.println("Acount Homder Name: " + obj.getAccountHolderName());
		System.out.println("Account Balance: " + obj.getBalance());

This program shows you to hide the variables using the private modifier:

	private String accounNumber;
	private String accountHolderName;
	private double currentBalance;

Then we can set and access the data using the public methods. If you run the example it will give the following output:

Acount Number: 1538666
Acount Homder Name: Deepak Kumar
Account Balance: 1000.0

Check more Core Java Tutorials in Java programming section.

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics