I studied the StringTokenizer.java class, and there were a few questions that came to mind.
I noticed that public methods that should be used by other classes called some kind of private method that did all the work. Now I know that one of the principles of OOD is that you can do as you can and hide all implementation details. I'm not sure I fully understand the logic behind this.
I understand that it is important to close the fields to prevent invalid values โโin them (only one of many reasons). However, when it comes to private methods, I'm not sure why they are just as important.
For example, in the case of the StringTokenizer class, StringTokenizer we just put all the implementation code in public methods? How would this affect the classes that use these methods, since the API for these methods (i.e., the Rules for calling these public methods) would remain the same? The only reason I can think about why private methods are useful is because it helps you write duplicate code. For example, if all public methods did the same, then you can declare a private method that performs this task and that can be used by public methods.
Another question: what is the advantage of writing an implementation in a private method as opposed to a public method?
Here is a small example:
public class Sum{ private int sum(int a, int b){ return a+b; } public int getSum(int a, int b){ return sum(a,b); } }
Vs ...
public class Sum{ public int getSum(int a, int b){ return a+b; } }
How is the first example more useful?
java encapsulation stringtokenizer public-method
kpatelio Oct 13 '11 at 3:12 2011-10-13 03:12
source share