Java Reference
In-Depth Information
private String author = "No Author";
private String title;
private double price;
private int pages;
private char binding = 'P'; // for paperback
private boolean inStock = true;
}
Now, when an object is created,
author
,
binding
, and
inStock
will be set to the specified values while
title
,
price
, and
pages
will assume the default values. A variable is given a default value only if no explicit value is assigned
to it. Suppose we create an object
b
with this:
Book b = new Book();
The fields will be initialized as follows:
•
author
is set to
"No Author"
. // specified in the declaration
•
title
is set to
null
. // default for (
String
) object type
•
price
is set to
0.0
. // default for numeric type
•
pages
is set to
0
. // default for numeric type
•
binding
is set to
'P'
. // specified in the declaration
•
inStock
is set to
true
. // specified in the declaration
2.3 Constructors
Constructors provide more flexible ways of initializing the state of an object when it is created. In the following
statement,
Book()
is termed a
constructor
:
Book b = new Book();
It is similar to a method call. But, you might say, we did not write any such method in our class definition. True,
but in such cases, Java provides a
default constructor
—one with no arguments (also called a
no-arg
constructor). The
default constructor is quite simplistic; it just sets the values of the instance variables to their default initial values.
Later, we could assign more meaningful values to the object's fields, as in the following:
b.author = "Noel Kalicharan";
b.title = "DigitalMath";
b.price = 29.95;
b.pages = 200;
b.binding = 'P'; //for paperback
b.inStock = true; //stock is available
Now suppose that when we create a book object, we want Java to assign the author and title automatically.
We want to be able to use statements such as the following for creating new book objects:
Book b = new Book("Noel Kalicharan", "DigitalMath");
Search WWH ::
Custom Search