Prev Main Next

Naming Functions


Same class

If you use a function in the same class where that function is defined, then you just call it by its name.

Example. A number is defined to be perfect if it is equal to the sum of all of its divisors. For example, 6 is perfect because the divisors of 6 are 1, 2 and 3, and 6 = 1 + 2 + 3. Here is a class that defines functions main and isperfect. Notice that, when main uses isperfect, it just calls it isperfect.

  public class Example
  {
    public static void main(String[] args)
    {
      int n;
      for(n = 1; n < 10000; n++) 
      {
        if(isperfect(n)) 
        {
          System.out.println(n + " is perfect");
        }
      }
    }

    public static boolean isperfect(int n)
    {
      //------------------------------------------
      // Set sum to the sum of the divisors of n.
      //------------------------------------------

      int k, sum;
      sum = 0;
      for(k = 1; k < n; k++) 
      {
        if(n % k == 0) sum = sum + k;
      }

      //---------------------------------------
      // Check whether the sum is equal to n.
      //---------------------------------------

      if(n == sum) return true;
      else return false;
    }
  }


Different class

If you use a function in a different class from where the function is defined, then you add the class name to the function name, in the form classname.functionname.

Example. Here is the same program, but it uses two classes. The isperfect function is in a different class from main. Notice how main uses isperfect.

  public class Example
  {
    public static void main(String[] args)
    {
      int n;
      for(n = 1; n < 10000; n++) 
      {
        if(Perfection.isperfect(n)) 
        {
          System.out.println(n + " is perfect");
        }
      }
    }
  }

  class Perfection
  {
    public static boolean isperfect(int n)
    {
      //------------------------------------------
      // Set sum to the sum of the divisors of n.
      //------------------------------------------

      int k, sum;
      sum = 0;
      for(k = 1; k < n; k++) 
      {
        if(n % k == 0) sum = sum + k;
      }

      //---------------------------------------
      // Check whether the sum is equal to n.
      //---------------------------------------

      if(n == sum) return true;
      else return false;
    }
  }


Prev Main Next