<< Chapter < Page | Chapter >> Page > |
DEFAULT_PRICE
is set as soon as the class is loaded and is displayed in the Constant area.song1
is allocated and contains the null value.computePrice
is called; it returns a value which stored in the field
price
.song1
.song2
.
Since the constructor is called with just two parameters (for
name
and
seconds
),
the second constructor is executed.The value of the field
pricePerSecond
is assigned from the constant, not from a parameter.
Exercise Modify the class to include a constructor with one parameter for the
name
and with a default song length of three minutes.
Exercise Modify the class to include a constructor with no parameters, so that all fields receive default values. Is there any meaning to the following constructor?
Song() {
}
Concept Constructors can be
overloaded like other methods. A method is overloaded when there is more than one method with the same name; the parameter signature is used to decide which method to call. For constructors, overloading is usually done when some of the fields of an object can be initialized with default values, although we want to retain
the possibility of explicitly supplying all the initial values. In such cases, it is convenient to invoke one constructor from within another in order to avoid duplicating code. Invoking the method
this
within one constructor calls another constructor
with the appropriate parameter signature.
Program: Constructor04.java
// Learning Object Constructor04
// invoking one constructor from anotherclass Song {
String name; int seconds;
double pricePerSecond; double price;
final static double DEFAULT_PRICE = 0.005;
Song(String n, int s, double p) { name = n;
seconds = s; pricePerSecond = p;
price = computePrice(); }
Song(String n, int s) {
this(n, s, DEFAULT_PRICE); }
private double computePrice() {
return seconds * pricePerSecond; }
}
public class Constructor04 { public static void main(/*String[] args*/) { Song song1 = new Song("Waterloo", 164);
}}
The website charges a uniform price per second for all songs, except for special offers. We define two constructors, one that specifies a price for special offers and another that uses a default price for ordinary songs.
DEFAULT_PRICE
is set as soon as the class is loaded and is displayed in the Constant area.song1
is allocated and contains the null value.this
means: call a
constructor from
this class. This constructor initializes the first three fields from the parameters, and the value of the fourth field is computed by calling the method
computePrice
.song1
.Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?