Section A.2. Method Declarations

[Page 544 (continued)]

A.2. Method Declarations

Declare a method by specifying the visibility, the return type, the method name, and a parameter list. Method declarations are usually followed by code inside of curly braces which are the statements that will be executed when the method is invoked.

visibility returnType name(parameterList) {   // statements in the method }

The parameter list is a comma-separated list of the parameters that will be passed to the method. For each parameter, specify a type and a name. Parameters are passed by value, which means that a copy of the value is passed to the method. So primitive variables passed to a method will not be affected by changes in the method after the return from the method, but because the value of an object variable is a reference to the object, a method can change the passed object, and such changes are preserved after the return from the method.

[Page 545]

public void changeRedAndGreen(double redMult,                               double greenMult)

The convention is to start a method name with lowercase letters and uppercase the first letter of each additional word. A method can return a value by using the return statement. The type of the value being returned must match the specified return type.

/**  * Method to create a new picture by rotating the current  * picture by the given degrees  * @param degrees the number of degrees to rotate by  * @return the resulting picture  */ public Picture rotate(int degrees) {   // create a new picture object big enough to hold the result   // no matter what the rotation is   Picture result = new Picture((int) (Math.ceil(rect.getWidth())),                                (int) (Math.ceil(rect.getHeight())));   // other statements in the method   return result; }

If a method doesn't return any value, the return type should be void.

/**  * Method to decrease the green in the picture by 30%  */ public void decreaseGreen() {   // method statements }

If you want all other classes to be able to invoke a method, make the visibility of the method public. If you only want to use a method in the class it is declared in, then use private as the visibility. If you leave off the visibility, then the method can be invoked by all classes in the same package. This is called package visibility. You can also use protected visibility if you want subclasses to be able to override an inherited method, but be aware that all classes in the same package also have access to the method.

Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Year: 2007
Pages: 191 © 2008-2017.
If you may any questions please contact us: