Initializing Objects with Constructors

As mentioned in Section 3.5, when an object of class GradeBook (Fig. 3.7) is created, its instance variable courseName is initialized to null by default. What if you want to provide a course name when you create a GradeBook object? Each class you declare can provide a constructor that can be used to initialize an object of a class when the object is created. In fact, Java requires a constructor call for every object that is created. Keyword new calls the class's constructor to perform the initialization. The constructor call is indicated by the class name followed by parentheses. For example, line 14 of Fig. 3.8 first uses new to create a GradeBook object. The empty parentheses after "new GradeBook" indicate a call to the class's constructor without arguments. By default, the compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor.

When you declare a class, you can provide your own constructor to specify custom initialization for objects of your class. For example, a programmer might want to specify a course name for a GradeBook object when the object is created, as in

 GradeBook myGradeBook =
 new GradeBook( "CS101 Introduction to Java Programming" );

In this case, the argument "CS101 Introduction to Java Programming" is passed to the GradeBook object's constructor and used to initialize the courseName. The preceding statement requires that the class provide a constructor with a String parameter. Figure 3.10 contains a modified GradeBook class with such a constructor.

Figure 3.10. GradeBook class with a constructor that receives a course name.

(This item is displayed on pages 97 - 98 in the print version)

 1 // Fig. 3.10:
 2 // GradeBook class with a constructor to initialize the course name.
 4 public class GradeBook
 5 {
 6 private String courseName; // course name for this GradeBook
 8 // constructor initializes courseName with String supplied as argument
 9 public GradeBook( String name ) 
10 { 
11  courseName = name; // initializes courseName 
12 } // end constructor 
14 // method to set the course name
15 public void setCourseName( String name )
16 {
17 courseName = name; // store the course name
18 } // end method setCourseName
20 // method to retrieve the course name
21 public String getCourseName()
22 {
23 return courseName;
24 } // end method getCourseName
26 // display a welcome message to the GradeBook user
27 public void displayMessage()
28 {
29 // this statement calls getCourseName to get the
30 // name of the course this GradeBook represents
31 System.out.printf( "Welcome to the grade book for
32 getCourseName() );
33 } // end method displayMessage
35 } // end class GradeBook

Lines 912 declare the constructor for class GradeBook. A constructor must have the same name as its class. Like a method, a constructor specifies in its parameter list the data it requires to perform its task. When you create a new object, this data is placed in the parentheses that follow the class name. Line 9 indicates that class GradeBook's constructor has a parameter called name of type String. In line 11 of the constructor's body, the name passed to the constructor is assigned to instance variable courseName.

Figure 3.11 demonstrates initializing GradeBook objects using this constructor. Lines 1112 create and initialize a GradeBook object. The constructor of class GradeBook is called with the argument "CS101 Introduction to Java Programming" to initialize the course name. The class instance creation expression to the right of = in lines 1112 returns a reference to the new object, which is assigned to variable gradeBook1. Lines 1314 repeat this process for another GradeBook object, this time passing the argument "CS102 Data Structures in Java" to initialize the course name for gradeBook2. Lines 1720 use each object's getCourseName method to obtain the course names and show that they were indeed initialized when the objects were created. In the introduction to Section 3.5, you learned that each instance (i.e., object) of a class contains its own copy of the class's instance variables. The output confirms that each GradeBook maintains its own copy of instance variable courseName.

Figure 3.11. Constructor used to initialize GradeBook objects.

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

 1 // Fig. 3.11:
 2 // GradeBook constructor used to specify the course name at the
 3 // time each GradeBook object is created.
 5 public class GradeBookTest
 6 {
 7 // main method begins program execution
 8 public static void main( String args[] )
 9 {
10 // create GradeBook object
11 GradeBook gradeBook1 = new GradeBook( 
12  "CS101 Introduction to Java Programming" );
13 GradeBook gradeBook2 = new GradeBook( 
14  "CS102 Data Structures in Java" ); 
16 // display initial value of courseName for each GradeBook
17 System.out.printf( "gradeBook1 course name is: %s
18 gradeBook1.getCourseName() );
19 System.out.printf( "gradeBook2 course name is: %s
20 gradeBook2.getCourseName() );
21 } // end main
23 } // end class GradeBookTest
gradeBook1 course name is: CS101 Introduction to Java Programming
gradeBook2 course name is: CS102 Data Structures in Java

Like methods, constructors also can take arguments. However, an important difference between constructors and methods is that constructors cannot return values, so they cannot specify a return type (not even void). Normally, constructors are declared public. If a class does not include a constructor, the class's instance variables are initialized to their default values. If a programmer declares any constructors for a class, Java will not create a default constructor for that class.

Error-Prevention Tip 3.1

Unless default initialization of your class's instance variables is acceptable, provide a constructor to ensure that your class's instance variables are properly initialized with meaningful values when each new object of your class is created.


Adding the Constructor to Class GradeBook's UML Class Diagram

The UML class diagram of Fig. 3.12 models class GradeBook of Fig. 3.10, which has a constructor that has a name parameter of type String. Like operations, the UML models constructors in the third compartment of a class in a class diagram. To distinguish a constructor from a class's operations, the UML places the word "constructor" between guillemets (« and ») before the constructor's name. It is customary to list constructors before other operations in the third compartment.

Figure 3.12 . UML class diagram indicating that class GradeBook has a constructor that has a name parameter of UML type String.

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

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


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


Searching and Sorting

Data Structures



Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2



Accessing Databases with JDBC


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

show all menu

Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon © 2008-2017.
If you may any questions please contact us: