+ 1

What is the use of private access specifier if it can't be accessed out of the class?

19th Oct 2016, 3:50 PM
Jaya
2 ответов
+ 8
It can be accessed by get property, others won't be able to change the value of it. Besides it can be seen in the classes that are inherited from the class with private fields
19th Oct 2016, 4:03 PM
Remmae
Remmae - avatar
+ 3
You can still provide getters and setters to allow access from outside, if you so wish. In general, it's a good idea to declare all attributes (which as a whole represent the state of the object) as private (or protected). An advantage of encapsulation is that it allows you to separate interface (ie what you provide to the outside to use the class) from the implementation. That way, you can change the implementation at any time without needing to also correct all the lines outside your class that were using your old implementation. Also, it prevents the user from setting the state of your object to an incoherent one. For example, let's say you have a class to represent a list and want to store the length of your list as an attribute. Allowing the length to be changed from the outside without adding or deleting an element would result in the stored length to not correspond to the actual length of your list, and you don't want that.
19th Oct 2016, 4:48 PM
Zen
Zen - avatar