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.
E.g:
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){ this.currentBalance=balance; } public double getBalance(){ return currentBalance; } public void setAccountNumber(String accounNumber){ this.accounNumber=accounNumber; } public String getAccountNumber(){ return accounNumber; } public void setAccountHolderName(String accountHolderName){ this.accountHolderName=accountHolderName; } public String getAccountHolderName(){ return accountHolderName; } public static void main(String[] args) { BankAccount obj = new BankAccount(); obj.setAccountNumber("1538666"); obj.setAccountHolderName("Deepak Kumar"); obj.setBalance(1000); 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.
[ 0 ] Comments