0
Can anyone explain any real time example with encapsulation?
Hii .Iam new to java programming.I have some difficulty with encapsulation concept.Can anyone explain what is the use of encapsulation with real time example?
5 ответов
0
Thank you Niush.😊
0
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.Other way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.
https://code.sololearn.com/cyZBwwQR0M88/?ref=app
if you create a class with its own method and variable and specific action within class that is encapsulation.
0
Thanks a lot chalana😊
0
It seems that you're already see how it works so i wont explain much.
Why do we encapsulate a data/state of an object and create getter setter ?. So outside code cant interfere with it. For example you have an instance variable that has some requirement, lets say a userid with specific format. If we dont encapsulate this data and let the outside code freely access the userid they'll be able to change it without following the specific format, thats why we need to hide the userid and create a setter method to filter the change, and getter so it can be read again
class User{
private String id; //encapsulate
public boolean setId(String newid){
if(!newId.matches("^\\d{3}[a-z]{7}quot;) return false;
id=newId;
return true;
}
public String getId(){
return id;
}
}
0
Nice example 😊Thank you taste.