Private Methods

In this lesson, we will explore the methods that contribute to a class's implementation but are not available to the public.

Methods that call other methods

We know that one method can call another. The invoked method can belong to a different class or to the same class as the method that calls it. For example, in the class Name, the method setName invokes setFirst and setLast. In this case, all three methods belong to the same class. The invoked methods are also public.

Sometimes the methods that a method calls are not suitable for use by the client of the class. Such methods usually perform only a part of computation and are called by a method to help it complete its task. We make these methods private instead of public.

Consider the class CalendarDate, discussed in the previous lesson. Both the constructor and the method setDate initialize the data fields month, day, and year. To eliminate this duplicated effort, we could replace the constructor’s three assignment statements with a call to setDate as follows:

Get hands-on with 1200+ tech skills courses.