Chapter 6 Methods 253 43 // square method (Free web host)

Chapter 6 Methods 253 43 // square method definition 44 public int square( int y ) 45 { 46 return y * y; // return square of y 47 48 } // end method square 49 50 } // end class SquareIntegers Fig. 6.3 Using programmer-defined method square(part 2 of 2). Note that we declared references output, outputAreaand containerand variable result as local variables in init, because they are used only in init. Variables should be declared as instance variables only if they are required for use in more than one method of the class or if the program should save their values between calls to the class s methods. Also, note that method init calls method square directly without preceding the method name with a class name and a dot operator or a reference name and a dot operator. Each method in a class is able to call the class s other methods directly. However, there is an exception to this rule. A class s static methods can call only other static methods of the class directly. Chapter 8 discusses staticmethods in detail. The definition of method square (line 44) shows that square expects an integer parameter y; square uses this name to manipulate the value it receives. Keyword int preceding the name of the method indicates that square returns an integer result. The returnstatement in squarepasses the result of the calculation y*yback to the calling method. Note that the entire method definition appears between the braces of the class SquareInt. All methods must be defined inside a class definition. Good Programming Practice 6.2 Place a blank line between method definitions to separate the methods and enhance program readability. Common Programming Error 6.2 Defining a method outside the braces of a class definition is a syntax error. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply