why we use encapsulation in java?
1- data controling(数据掌控)
Imaging if you set a person class, and you don’t want his/ her age beyond 200. so, you can set the code into setMethod to control the age under 200.( if age < 200)
2- data security(数据安全)
Private data members cannot be accessed from other class or package.
3 - easy for testing(方便测试)
traking the error more easier.
Java中的封装是重要的编程原则,它包括数据控制、数据安全和便于测试。通过封装,可以限制对类成员的访问,确保数据在合理范围内,如设置年龄上限。同时,私有成员变量无法从外部直接访问,保护了数据的安全性。此外,封装也简化了单元测试,使错误定位更加容易。
191

被折叠的 条评论
为什么被折叠?



