Recall that we commonly store the useful methods (such as isPalindrome( )) in a separate class:
public class Tools { public static boolean isPalindrome(String w) // The original palindrome( ) method { int lastPos = w.length()-1; return isPalindrome(w, 0, lastPos); } public static boolean isPalindrome(String w, int startPos, int endPos) { if ( startPos >= endPos ) { // Base case return true; } else { // Solve a smaller problem that helps us solve the original problem boolean helpSol = isPalindrome(w, startPos+1, endPos-1); return (w.charAt(startPos) == w.charAt(endPos)) && helpSol; } } } |
Result: both isPalindrome( ) methods can be used:
public class UsePalindrome
{
public static void main(String[] args)
{
String s = "racecar";
boolean ans;
ans = Tools.isPalindrome(s);
// We can call isPalindrome(String w)
ans = Tools.isPalindrome(s, 0, s.length()-1);
// We can also call
// isPalindrome(String w, startPos, endPos)
}
}
|
Reason: they are public methods
|
DEMO: demo/07-recursion/03-public/Tools.java + UsePalindrome.java
Suppose: we want to disallow other classes from using the isPalindrome(w, startPos, endPos) method:
public class Tools
{
public static boolean isPalindrome(String w)
{
int lastPos = w.length()-1;
return isPalindrome(w, 0, lastPos);
}
// Other classes can not use this helper method:
public static boolean isPalindrome(String w, int startPos, int endPos)
{
...
}
}
|
Afterall, the isPalindrome(w, startPos, lastPos) was a helper method to make the implementation more efficient
$64,000 question: how can we prevent other classes from using/invoking some methods in a class ?
|
DEMO: demo/07-recursion/04-private/Tools.java + UsePalindrome.java