Building And Testing The Person Class


Methods

A methods is a named module of executable program functionality. A method can contain program statements that, when grouped together, represent a basic level of code reuse. You access the functionality of a method by calling the method using its name in a program. (I use the term program here to mean any piece of code that could possibly use the services of the class that defines the method. This might include 1) another method within the class you are defining, 2) another class within your program, or 3) a third-party program that wants to use the services provided by your program.)

In the Java language a method must belong to a class; they cannot exist or be defined outside of a class construct.

Method Naming — Use Action Words That Indicate The Method’s Purpose

When naming a method use action words (verbs) that provide an indication of the method’s intended purpose. I discussed method naming guidelines in chapter 1 in the section titled Identifier Naming — Writing Self-Commenting Code.

Maximize Method Cohesion

The first rule-of-thumb to keep in mind when writing a method is to keep the functionality of the method focused on the task at hand. The formal term used to describe a method’s focus characteristic is cohesion. The goal is to write highly-cohesive methods. A method that does things it really shouldn’t be doing is not focused and is referred to as minimally cohesive. You can easily write cohesive methods if you follow this two-step approach:

  • Step 1 - Follow the advice offered in the previous sub-section and start with a good method name. The name of the method must indicate the method’s intended purpose.

  • Step 2 - Keep the method’s body code focused on performing the task indicated by the method’s name. A well-named, maximally-cohesive method will pull no surprises!

Sounds simple enough — but if you’re not careful you can slip functionality into a method that doesn’t belong there. Sometimes you will do this because you are lazy, and sometimes it will happen no matter how hard you try to avoid doing so. Practice makes perfect!

Structure Of A Method Definition

A method definition declares and implements a method. A method definition consists of several optional and mandatory components. These include method modifiers, a return type or void, method name, parameter list, and throws clause. I discuss these method components in detail below. Figure 9-5 shows the structure of a method definition.

image from book

 method_modifiersopt return_type or voidopt method_name( parameter_listopt) throwsopt {              // method body - program statements go here       }

image from book

Figure 9-5: Method Definition Structure

Any piece of the method definition structure shown in figure 9-5 that’s labeled with the subscript opt is optional and can be omitted from a method definition depending on the method’s required behavior. In this chapter I will focus on just a few of the potentially many method variations you can write. You will be gradually introduced to different method variations and as you progress through the book. The following sections describe each piece of the method definition structure in more detail.

Method Modifiers (optional)

Use method modifiers to specify a particular aspect of method behavior. Table 9-2 lists and describes the Java keywords that can be used as method modifiers.

Table 9-2: Java Method Modifier Keywords

Modifier

Description

public

The public keyword declares the method’s accessibility to be public. Public methods can be accessed by client code. ( i.e., grants horizontal access to the method )

protected

The protected keyword declares the method’s accessibility to be protected. Protected accessibility prevents horizontal access but allows the method to be inherited by derived classes.

private

The private keyword declares the method’s accessibility to be private. It prevents both horizontal access and method inheritance.

abstract

The abstract keyword is used to declare a method that contains no body ( no implementation ). The purpose of an abstract method is to defer the implementation of a method’s functionality to a subclass. Abstract methods are discussed in chapter 11.

static

The static keyword is used to create a static or class method.

final

The final keyword is used to specify that a method cannot be overridden or hidden by a subclass method. Final methods are covered in chapter 11.

synchronized

The synchronized keyword is used to specify that a method requires a lock before it executes. Synchronized methods are used in multi-threaded programming and are covered in detail in chapter 16.

native

The native keyword is used to declare a native method. A native method serves as a declaration only and the implementation of the method will be written in another programming language like C or C++. Native method code executes directly on the hardware vice in the Java virtual machine environment.

strictfp

The strictfp keyword makes all float or double expressions within the body of the method explicitly FP-strict. For more information about the strictfp keyword or FP-strict expressions refer to The Java Language Specification, Second Edition which is listed in the references section at the end of this chapter.

Return Type or void (optional)

A method can return a result as a side effect of its execution. If you intend for a method to return a result you must specify the return type of the result. If the method does not return a result then you must use the keyword “void”.

The return type and void are optional because constructor methods return neither. Constructor methods are discussed in detail below.

Method Name (mandatory)

The method name is mandatory. As was discussed earlier you should use verbs in method names since methods perform some sort of action. If you chose to ignore good method naming techniques you will find that your code is hard, if not impossible, to read and understand and as a result will also be hard to fix if it’s broken.

Parameter List (optional)

A method can specify one or more formal parameters. Each formal parameter has a type and a name. The name of the parameter has local scope within the body of the method and hides any field members having the same name.

Method Body (optional for abstract or native methods)

The method body is denoted by a set of opening and closing brackets. Any code that appears between a method’s opening and closing brackets is said to be in the body of the method. If you are declaring an abstract or native method you will omit the braces and terminate the method declaration with a semicolon.

Example Method Definitions

This section offers a few examples of method definitions. The body code is omitted so that you can focus on the structure of each method definition. The following line of code would define a method that returns a String object that represents the first name of some object (perhaps a Person object).

 public String getFirstName(){ // body code goes here }

Notice that the above method definition uses the public access modifier, declares a return type of String, and takes no arguments because it declares no parameters. The name of the method is getFirstName which does a good job of describing the method’s purpose.

The next method declaration might be used to set an object’s first name:

 public void setFirstName(String first_name){ // body code goes here }

This method is also public but it does not return a result hence the use of the keyword void. It contains one parameter named first_name that is of type String.

The following method definition might be used to get a Person object’s age:

 public int getAge(){ // body code goes here }

This method is public and returns an integer primitive type result. It takes no arguments. See if you can guess what type of method is being defined by the following definition:

 public Person(String f_name, String m_name, String l_name){      // body code goes here    }

If you guessed that it was a constructor method you would be right. Constructor methods have no return type, not even void. This particular constructor declares three formal parameters having type String. Constructors are discuss in detail below.

Method Signatures

Methods have a distinguishing characteristic known as a signature. A method’s signature consists of its name and the number and types of its parameters. Method modifiers and return types are not part of a method’s signature. It’s important to understand the concept of method signature so that you can understand the concept of method overloading which is discussed in the next section.

Methods with different names and the same parameter list have different signatures. Methods with the same name and different parameter lists have different signatures as well and are said to be overloaded (because they share the same name). Methods cannot have the same name and identical parameter lists. This will cause a compiler error.

Overloading Methods

A class can define more than one method with the same name but having different signatures. This is referred to as method overloading. You would overload methods when the method performs the same function but in a slightly different way or on different argument types. The most commonly overloaded method is the class constructor. You will see many examples of overloaded class constructors throughout the remaining chapters of this book.

Another frequently encountered method overloading scenario occurs when you want to provide a public method for horizontal access but actually do the work behind the scenes with a private method. The only rule, as stated above, is that each method must have a different signature, which means their names can be the same but their parameter lists must be different in some way. The fact that one is public and the other is private has no bearing on their signatures.

Constructor Methods

Constructor methods are special methods whose purpose is to set up or build the object in memory when it is created. You can chose not to define a constructor method for a particular class if you desire. In this case the Java compiler will create a default constructor for you. This default constructor will usually not provide the level of functionality you require except perhaps in the case of very simple or trivial class declarations. If you want to be sure of the state of an object when it is created you must define one or more constructor methods.

Quick Review

Methods are named modules of executable program functionality. Methods contain program statements that, when grouped together, represent a basic level of code reuse. You access the functionality of a method by calling the method using its name in a program.

Methods should be well-named and maximally cohesive. A well-named, maximally-cohesive method will pull no surprises!

Method definitions have structure. Their behavior can be optionally modified with method modifiers, they can optionally specify a return result type or void, and they can have an optional parameter list.

Methods have a distinguishing characteristic known as a method signature. Methods with different names and parameter lists are said to have different signatures. Methods with different names and the same parameter list also have different signatures. Methods with the same name and different parameter lists have different signatures as well and are said to be overloaded (because they share the same name). Methods cannot have the same name and identical parameter lists. This will cause a compiler error.

Constructor methods are used to set up or build an object when it’s created in memory. Java will provide a default constructor but it may or may not provide the level of functionality you require.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net