Java Reference
In-Depth Information
We can do this, but we must first write an appropriate constructor, one defined with two
String
parameters.
The following shows how it can be done:
public Book(String a, String t) {
author = a;
title = t;
}
Here are some important points to note:
•
A constructor for a class has the
same name
as the class. Our class is called
Book
; therefore, the
constructor must be called
Book
. Since a constructor is meant to be used by other classes, it is
declared
public
.
A constructor can have zero or more parameters. When called, the constructor must be given
•
the appropriate number and type of arguments. In our example, the constructor is declared
with two
String
parameters,
a
and
t
. When calling the constructor, two
String
arguments
must be supplied.
•
The body of the constructor contains the code that would be executed when the constructor
is called. Our example sets the instance variable
author
to the first argument and
title
to the
second argument. In general, we can have statements other than those that set the values of
instance variables. We can, for instance, validate a supplied value before assigning it to a field.
We will see an example of this in the next section.
•
A constructor does not have a return type, not even
void
.
If initial values are provided for instance variables in their declaration, those values are stored
•
before
the constructor is called.
For example, suppose the class
Book
is now declared as follows:
public class Book {
private static double Discount = 0.25;
private static int MinBooks = 5;
private String author = "No Author";
private String title;
private double price;
private int pages;
private char binding = 'P'; // for paperback
private boolean inStock = true;
public Book(String a, String t) {
author = a;
title = t;
}
} //end class Book
The statement
Book b = new Book("Noel Kalicharan", "DigitalMath");
Search WWH ::
Custom Search