Java Reference
In-Depth Information
LISTING 9.10
//********************************************************************
// FoodAnalyzer.java Author: Lewis/Loftus
//
// Demonstrates indirect access to inherited private members.
//********************************************************************
public class FoodAnalyzer
{
//-----------------------------------------------------------------
// Instantiates a Pizza object and prints its calories per
// serving.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Pizza special = new Pizza (275);
System.out.println ("Calories per serving: " +
special.caloriesPerServing());
}
}
OUTPUT
Calories per serving: 309
object and invokes a method to determine how many calories the pizza has per
serving due to its fat content.
The FoodItem class shown in Listing 9.11 represents a generic type of food.
The constructor of FoodItem accepts the number of grams of fat and the number
of servings of that food. The calories method returns the number of calories
due to fat, which the caloriesPerServing method invokes to help compute the
number of fat calories per serving.
The Pizza class, shown in Listing 9.12, is derived from the FoodItem class,
but it adds no special functionality or data. Its constructor calls the constructor of
FoodItem using the super reference, asserting that there are eight servings per pizza.
The Pizza object called special in the main method is used to invoke the
method caloriesPerServing , which is defined as a public method of FoodItem .
Note that caloriesPerServing calls calories , which is declared with private vis-
ibility. Furthermore, calories references the variable fatGrams and the constant
CALORIES_PER_GRAM , which are also declared with private visibility.
 
Search WWH ::




Custom Search