Sunday, October 28, 2018

Encapsulation in Java

What is encapsulation?


Encapsulation is the way of facilitating data abstraction. Data variables and methods can be binded together or en'capsulated' in a template called Class.
Consider a Car as an example. It has an encapsulated method runEngineToDrive().

runEngineToDrive()

As the class Car encapsulated the behavior runEngineToDrive(), if any new techniques are found to improve the engine efficiency, the class can implement the techniques in the method without the need for the users to worry about it. As the way of accessing class behavior/method w.r.t the user is not changed, the class can fully control the behavior on it's own.


This is possible because of this great Object Oriented feature encapsulation.

I can explain encapsulation with another real programming example


This example deals with the implementation of credit card transactions.




Every CreditCard must implement a behavior/method to pay the money by swiping it in the swiping machines at stores. The swiping machine is the user here using a CreditCard class swipeCard() method to deduct the money from customer account.


public class CreditCard{
	public void swipeCard(){
		System.out.println("Deducting money for the transaction..");
	}
}




public class SwipingMachine {
	
	public static void main(String[] args) {
		
		CreditCard creditCard = new CreditCard();
		creditCard.swipeCard();
	}

}

Output : Deducting money for the transaction..



The credit card company decides to give a 5% cash back due to festival season and informed all the customers about the offer.




Now the programmers will update the swipeCard() method to deposit the 5% cash back to the users account without the swiping machine ( the user) to know about it. This is possible because the CreditCard class will control the behavior and not the user.
Now update the CreditCard class to add 5% cash back without updating anything in SwipingMachine..

public void swipeCard(){
		System.out.println("Deducting money for the transaction..");
		System.out.println("Credit 5% money for the transaction to customer account..");
	}

The output will be updated to:
 Deducting money for the transaction..
Credit 5% money for the transaction to customer account..

No comments:

Post a Comment