Private Methods Over Public Methods

后端 未结 7 756
醉酒成梦
醉酒成梦 2020-12-12 20:26

I was examining the StringTokenizer.java class and there were a few questions that came to mind.

I noticed that the public methods which are to be used

相关标签:
7条回答
  • 2020-12-12 21:13

    An advantage and also a good reason to use private methods inside public classes is for security and bug prevention. Methods that are declared as private are only accessible by the class they are part of. This means that your private method can't be accidentally called from else where within the program reducing bugs and other complications. If you declare your method as public it can be accessed by the whole problem and can cause complications.

    You may have a number of methods that work on a certain piece of data that you don't want any other part of the program to be able to interfere with. Using data encapsulation via private methods and/or variables helps to prevent this and also makes your code easier to follow and document.

    0 讨论(0)
提交回复
热议问题