Java – when should encapsulation be used?

I am completing the sun / Oracle trail( http://docs.oracle.com/javase/tutorial/java/TOC.html )And constantly reiterate the importance of packaging

How important is encapsulation really? I mean, if I may need to access the value of a given class field, why can I access the field directly through a method? Because in any case, the field will be accessed through the corresponding object. What's wrong with this?

Is it only for code extensibility purposes? In other words, because if I decide to change or disinfect the field in some way before returning to it, will I do so in the future?

I prefer one or two examples

Solution

verification.

If you do not use the method, you cannot add any validation on the field unless you validate it at every location where you want to access the field: unsustainable

It also separates your class data from the outside world By hiding the actual implementation of the data behind the method, you can manipulate the data as you want (now and in the future) without breaking other code segments This allows you to change the presentation of something without problems, as long as you ensure that it can still be returned through existing methods

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>