Incremental Java
Private Methods

Why Private Methods?

So far, we've made all methods public, and all instance variables private. An object user can use the public methods, but can't directly access private instance variables.

You can make methods private too. Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.

Let's think of a real-world example. Suppose you own a restaurant. Rather than clean the tablecloths yourself, you hire a company that takes the cloths, have them wash and clean it, and return it to you when they're done.

The customer doesn't really care about how the tablecloths are cleaned. All they care is that there is a nice tablecloth when they eat. In general, you don't want customers to call the cleaning company directly. You want to do that yourself.

Similarly, rather than write the entire code in one method definition, you might write a private method that does some of the work, and then you do the rest. Using private methods makes your code easier to read.

Example

Imagine we have a SodaMachine class with three products: Coke, Sprite, and Fanta.

The soda machine keeps track of how many cans are left in the machine. You want to find out the total worth of all cans in the machine. This is the total number of cans multiplied by the cost of each can. Let's say each can has the same cost.

Here's how you could implement a public method getTotalCost() using a private method called getTotalCans().

public class SodaMachine
{
   private int numCokeCans, numSpriteCans, numFantaCans ;
   private int costPerCan ;

   // Public method body uses private method, getTotalCans()
   public int getTotalCost()
   {
      return getTotalCans() * costPerCan ;
   }

   // Private method.  Can only be used by methods in SodaMachine
   private int getTotalCans()
   {
      return numCokeCans + numSpriteCans + numFantaCans ;
   }
}
You may notice something odd. We're calling getTotalCans() Where's the object? Shouldn't there be an object? In fact, there is an object. It's this.

getTotalCans() is short for this.getTotalCans(). Recall that this is the name of the object when we're inside the class definition. Outside it may have a different name. It might have been declared as foo, bar or who knows what.

However, we want the name to be the same on the inside so we don't care which object it is. (This is just like someone who calls everyone "Bud", because they don't want to have to remember their name. "Bud" becomes the whichever person they are talking at the current moment).