Java Reference
In-Depth Information
will be executed as follows:
1.
Storage is found for a
Book
object, and the address of the storage is stored in b.
2.
The fields are set 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
3.
The constructor is called with arguments
"Noel Kalicharan"
and
"DigitalMath"
; this
sets
author
to
"Noel Kalicharan"
and
title
to
"DigitalMath"
, leaving the other fields
untouched. When the constructor is finished, the fields will have the following values:
author "Noel Kalicharan"
title "DigitalMath"
price 0.0
pages 0
binding 'P'
inStock true
2.3.1 Overloading a Constructor
Java allows us to have more than one constructor, provided each has a different
signature
. When several
constructors can have the same name, this is referred to as
overloading the constructor.
Suppose we want to be able
to use the no-arg constructor as well as the one with author and title arguments. We can include both in the class
declaration like this:
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() { }
public Book(String a, String t) {
author = a;
title = t;
}
} //end class Book
Search WWH ::
Custom Search