the use of private keyword

后端 未结 12 1773
栀梦
栀梦 2021-01-01 14:00

I am new to programming. I am learning Java now, there is something I am not really sure, that the use of private. Why programmer set the variable as private then write , ge

12条回答
  •  醉话见心
    2021-01-01 14:47

    It's a common pet-peeve of many programmers - Java code with private fields and public accessors and mutators. The effect is as you say, those fields might as well been public.

    There are programming languages that voice for the other extreme, too. Look at Python; just about everything is public, to some extent.

    These are different coding practices and a common thing programmers deal with every day. But in Java, here's my rule of thumb:

    • If the field is used purely as an attribute, both readable and writeable by anyone, make it public.
    • If the field is used internally only, use private. Provide a getter if you want read access, and provide a setter if you want write access.
    • There is a special case: sometimes, you want to process extra data when an attribute is accessed. In that case, you would provide both getters and setters, but inside these property functions, you would do more than just return - for example, if you want to track the number of times an attribute is read by other programs during an object's life time.

    That's just a brief overview on access levels. If you're interested, also read up on protected access.

提交回复
热议问题