Declaring a Class with a Method and Instantiating an Object of a Class

We begin with an example that consists of classes GradeBook (Fig. 3.1) and GradeBookTest (Fig. 3.2). Class GradeBook (declared in file GradeBook.java) will be used to display a message on the screen (Fig. 3.2) welcoming the instructor to the grade-book application. Class GradeBookTest (declared in file GradeBookTest.java) is an application class in which the main method will use class GradeBook. Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the .java file-name extension. Thus, classes GradeBook and GradeBookTest must be declared in separate files, because each class is declared public.

Figure 3.1. Class declaration with one method.

 1 // Fig. 3.1: GradeBook.java
 2 // Class declaration with one method.
 3
 4 public class GradeBook
 5 {
 6 // display a welcome message to the GradeBook user
 7 public void displayMessage()
 8 {
 9 System.out.println( "Welcome to the Grade Book!" );
10 } // end method displayMessage
11
12 } // end class GradeBook

Figure 3.2. Creating an object of class GradeBook and calling its displayMessage method.

(This item is displayed on page 86 in the print version)

 1 // Fig. 3.2: GradeBookTest.java
 2 // Create a GradeBook object and call its displayMessage method.
 3
 4 public class GradeBookTest
 5 {
 6 // main method begins program execution
 7 public static void main( String args[] )
 8 {
 9 // create a GradeBook object and assign it to myGradeBook
10 GradeBook myGradeBook = new GradeBook();
11
12 // call myGradeBook's displayMessage method
13 myGradeBook.displayMessage();
14 } // end main
15
16 } // end class GradeBookTest
 
Welcome to the Grade Book!
 

Common Programming Error 3.1

Declaring more than one public class in the same file is a compilation error.

 

Class GradeBook

The GradeBook class declaration (Fig. 3.1) contains a displayMessage method (lines 710) that displays a message on the screen. Line 9 of the class performs the work of displaying the message. Recall that a class is like a blueprintwe'll need to make an object of this class and call its method to get line 9 to execute and display its message.

The class declaration begins at line 4. The keyword public is an access modifier. For now, we will simply declare every class public. Every class declaration contains keyword class followed immediately by the class's name. Every class's body is enclosed in a pair of left and right braces ({ and }), as in lines 5 and 12 of class GradeBook.

In Chapter 2, each class we declared had one method named main. Class GradeBook also has one methoddisplayMessage (lines 710). Recall that main is a special method that is always called automatically by the Java Virtual Machine (JVM) when you execute an application. Most methods do not get called automatically. As you will soon see, you must call method displayMessage to tell it to perform its task.

The method declaration begins with keyword public to indicate that the method is "available to the public"that is, it can be called from outside the class declaration's body by methods of other classes. Keyword void indicates that this method will perform a task but will not return (i.e., give back) any information to its calling method when it completes its task. You have already used methods that return informationfor example, in Chapter 2 you used Scanner method nextInt to input an integer typed by the user at the keyboard. When nextInt inputs a value, it returns that value for use in the program.

The name of the method, displayMessage, follows the return type. By convention, method names begin with a lowercase first letter and all subsequent words in the name begin with a capital letter. The parentheses after the method name indicate that this is a method. An empty set of parentheses, as shown in line 7, indicates that this method does not require additional information to perform its task. Line 7 is commonly referred to as the method header. Every method's body is delimited by left and right braces ({ and }), as in lines 8 and 10.

The body of a method contains statement(s) that perform the method's task. In this case, the method contains one statement (line 9) that displays the message "Welcome to the Grade Book!" followed by a newline in the command window. After this statement executes, the method has completed its task.

Next, we'd like to use class GradeBook in an application. As you learned in Chapter 2, method main begins the execution of every application. A class that contains method main is a Java application. Such a class is special because the JVM can use main to begin execution. Class GradeBook is not an application because it does not contain main. Therefore, if you try to execute GradeBook by typing java GradeBook in the command window, you will get the error message:

 Exception in thread "main" java.lang.NoSuchMethodError: main

This was not a problem in Chapter 2, because every class you declared had a main method. To fix this problem for the GradeBook, we must either declare a separate class that contains a main method or place a main method in class GradeBook. To help you prepare for the larger programs you will encounter later in this book and in industry, we use a separate class (GradeBookTest in this example) containing method main to test each new class we create in this chapter.

Class GradeBookTest

The GradeBookTest class declaration (Fig. 3.2) contains the main method that will control our application's execution. Any class that contains main declared as shown on line 7 can be used to execute an application. This class declaration begins at line 4 and ends at line 16. The class contains only a main method, which is typical of many classes that begin an application's execution.

Lines 714 declare method main. Recall from Chapter 2 that the main header must appear as shown in line 7; otherwise, the application will not execute. A key part of enabling the JVM to locate and call method main to begin the application's execution is the static keyword (line 7), which indicates that main is a static method. A static method is special because it can be called without first creating an object of the class in which the method is declared. We thoroughly explain static methods in Chapter 6, Methods: A Deeper Look.

In this application, we'd like to call class GradeBook's displayMessage method to display the welcome message in the command window. Typically, you cannot call a method that belongs to another class until you create an object of that class, as shown in line 10. We begin by declaring variable myGradeBook. Note that the variable's type is GradeBookthe class we declared in Fig. 3.1. Each new class you create becomes a new type in Java that can be used to declare variables and create objects. Programmers can declare new class types as needed; this is one reason why Java is known as an extensible language.

Variable myGradeBook is initialized with the result of the class instance creation expression new GradeBook(). Keyword new creates a new object of the class specified to the right of the keyword (i.e., GradeBook). The parentheses to the right of the GradeBook are required. As you will learn in Section 3.7, those parentheses in combination with a class name represent a call to a constructor, which is similar to a method, but is used only at the time an object is created to initialize the object's data. In that section you will see that data can be placed in parentheses to specify initial values for the object's data. For now, we simply leave the parentheses empty.

Just as we can use object System.out to call methods print, printf and println, we can now use myGradeBook to call method displayMessage. Line 13 calls the method displayMessage (declared at lines 710 of Fig. 3.1) using variable myGradeBook followed by a dot separator (.), the method name displayMessage and an empty set of parentheses. This call causes the displayMessage method to perform its task. This method call differs from the method calls in Chapter 2 that displayed information in a command windoweach of those method calls provided arguments that specified the data to display. At the beginning of line 13, "myGradeBook." indicates that main should use the GradeBook object that was created on line 10. Line 7 of Fig. 3.1 indicates that method displayMessage has an empty parameter listthat is, displayMessage does not require additional information to perform its task. For this reason, the method call (line 13 of Fig. 3.2) specifies an empty set of parentheses after the method name to indicate that no arguments are being passed to method displayMessage. When method displayMessage completes its task, method main continues executing at line 14. This is the end of method main, so the program terminates.

Compiling an Application with Multiple Classes

You must compile the classes in Fig. 3.1 and Fig. 3.2 before you can execute the application. First, change to the directory that contains the application's source-code files. Next, type the command

 javac GradeBook.java GradeBookTest.java

to compile both classes at once. If the directory containing the application includes only the files for this application, you can compile all the classes in the directory with the command

 javac *.java

The asterisk (*) in *.java indicates that all files in the current directory that end with the file name extension ".java" should be compiled.

UML Class Diagram for Class GradeBook

Figure 3.3 presents a UML class diagram for class GradeBook of Fig. 3.1. Recall from Section 1.16 that the UML is a graphical language used by programmers to represent their object-oriented systems in a standardized manner. In the UML, each class is modeled in a class diagram as a rectangle with three compartments. The top compartment contains the name of the class centered horizontally in boldface type. The middle compartment contains the class's attributes, which correspond to instance variables in Java. In Fig. 3.3, the middle compartment is empty because the version of class GradeBook in Fig. 3.1 does not have any attributes. The bottom compartment contains the class's operations, which correspond to methods in Java. The UML models operations by listing the operation name followed by a set of parentheses. Class GradeBook has one method, displayMessage, so the bottom compartment of Fig. 3.3 lists one operation with this name. Method displayMessage does not require additional information to perform its tasks, so the parentheses following displayMessage in the class diagram are empty, just as they were in the method's declaration in line 7 of Fig. 3.1. The plus sign (+) in front of the operation name indicates that displayMessage is a public operation in the UML (i.e., a public method in Java). We will often use UML class diagrams to summarize a class's attributes and operations.

Figure 3.3. UML class diagram indicating that class GradeBook has a public displayMessage operation.


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

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