B.2. Declaring a Class with a Method and Instantiating an Object of a Class

In this section, you’ll create a new class, then use it to create an object. We begin by delcaring classes GradeBook (Fig. B.1) and GradeBookTest (Fig. B.2). Class GradeBook (declared in the file GradeBook.java) will be used to display a message on the screen (Fig. B.2) welcoming the instructor to the grade book application. Class GradeBookTest (declared in the file GradeBookTest.java) is an application class in which the main method will create and use an object of class GradeBook. Each class declaration that begins with keyword public must be stored in a file having the same name as the class and ending with the .java file-name extension. Thus, classes GradeBook and GradeBookTest must be declared in separate files, because each class is declared public.


 1   // Fig. B.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   } // end class GradeBook


Fig. B.1 | Class declaration with one method.


 1   // Fig. B.2: GradeBookTest.java
 2   // Creating a GradeBook object and calling 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   } // end class GradeBookTest

Welcome to the Grade Book!


Fig. B.2 | Creating a GradeBook object and calling its displayMessage method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset