Constructor
methods
The statement:
new
TextItem( "Deitel & Deitel", 1041, "Dei 304.167");
might result in the following object being
created in the computer's memory:
TextItem object
|
Variables
|
title
= "Deitel & Deitel" |
numPages
= 1041 |
shelfMark
= "Dei 304.167" |
onLoan
= false |
daysLate
= 0 |
Notice that the onLoan
status is false and the value of daysLate
is zero, even thought these values were not part of the statement. In fact,
even though values like "Deitel
& Deitel" were part of the statement,
how did they get into an object?
Statements that create objects are
actually invoking methods called constructor methods. Each class
has a constructor method that executes when a new object is to be created
of that class. We might define a constructor method for our TextItem class
as follows:
void
TextItem( String itemTitle,int itemNumPages,
String itemShelfMark )
{
//
use method arguments to initialise variables
title = itemTitle;
numPages =
itemNumPages;
shelfMark
= itemShelfMark;
// set some
default values for variables for new object
onLoan = false;
daysLate =
0;
}
As can be seen, for this constructor the
arguments to the method (title, number of pages and shelf mark) are used
to initialise some of this new object's variables. In addition, some variables
(onLoan
and daysLate)
are automatically initialised to values appropriate for a new object of
the class.
A method is recognized as a constructor
by having the same identifier (name) as the class, e.g.
TextItem.
All classes have constructor methods
that state what should be done to create a new object of the class. Sometimes
constructors are not explicit in the definition of the class (they may
be inherited from another class ?we'll look more at inheritance in the
next unit).
Constructors do not have to have arguments
?for some classes of objects there is some reasonable way create an object
that does not need to have any initial values provided.
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|