Organizing our methods

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;
      }
   }  
}

Organizing our methods

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

  • A method defined using public can be use/invoked by methods in any class

DEMO: demo/07-recursion/03-public/Tools.java + UsePalindrome.java

Organizing our methods

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 ?

The public and private modifiers

  • The public access modifier:

    • A public method in a class can be invoked from any (other) class

  • The private access modifier:

    • A private method in a class can only be invoked from inside the same class

  • We can prevent other classes from using/invoking the the helper method isPalindrome(w, startPos, endPos) by qualifying the helper method as private:

       private static boolean isPalindrome(String w, int startPos, int endPos) 
       {
          ...
       } 

DEMO: demo/07-recursion/04-private/Tools.java + UsePalindrome.java