the use of private keyword

后端 未结 12 1741
栀梦
栀梦 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 15:00

    The most important reason is to hide the internal implementation details of your class. If you prevent programmers from relying on those details, you can safely modify the implementation without worrying that you will break existing code that uses the class.

    So by declaring the field private you prevent a user from accessing the variable directly. By providing gettters and setters you control exactly how a user may control the variable.

提交回复
热议问题