Java OOPS - Data Hiding and Abstraction
We will learn how to achieve data hiding and abstraction in Java
Welcome to 2nd article of the Java OOPs series, in the previous article we learned about classes and objects.
In this, we will cover Data Hiding and Abstraction.
Data Hiding
Data hiding is basically hiding internal data(variables) from the outside world(other classes).
The outside class should not access the data directly.
For eg: Our bank account balance is not available directly to everyone, it is private to us.
Similarly, data hiding can be achieved programmatically by making the variables private.
It helps to keep our data secure and if any entity wants to access the data should be authenticated.
So, how to get private data?
For eg:- To get the account balance we go to the bank and provide them the account number and id proof then only they tell us the balance.
Similarly in Java using getters, we can implement all the logic of validation and then return the data to the entity which asked for it.
class Bank{
private long balance=0; // private data - data hiding
private int bank_id;
public long getBalance(int id){
//Checking user authorization
//Checking bank_id same as given id or not
if(this.bank_id==id){
return balance;
}
//Unauthorized User
return -1;
}
}
Abstraction
When something is not complete we call that abstract.
In oops, hiding internal operations is an abstraction.
Just highlight the set of services we offer, no need to provide implementation details.
For eg:- While sending a message to another person, we as users don't need to know how internally it is working, that is an abstraction.
Abstraction focuses on WHAT? and not on HOW?
How do we achieve Abstraction?
- Using Abstract Classes
- Using Interface - as all the methods are abstract, outside users have no idea about its implementation. So we can achieve abstraction.
Conclusion
In this article, we learned about Data Hiding and Abstraction and their importance.
In the next article, we will start with Encapsulation.
If you have any suggestions do comment below.
Thanks for Reading.