<< Chapter < Page | Chapter >> Page > |
Concept Constructors are often used simply for assigning initial values to fields of an object; however, an arbitrary initializing computation can be carried out within the constructor.
Program: Constructor02.java
// Learning Object Constructor02
// computation within constructorsclass Song {
String name; int seconds;
double pricePerSecond; double price;
Song(String n, int s, double p) {
name = n; seconds = s;
pricePerSecond = p; price = computePrice();
}
private double computePrice() { return seconds * pricePerSecond;
}}
public class Constructor02 {
public static void main(/*String[] args*/) {
Song song1 = new Song("Waterloo", 164, 0.01); }
}
The price of a song will not change as long as the fields
second
and
pricePerSecond
do not change; to avoid recomputing the price each time it is needed,
the class contains a field
price
whose value is computed
within the
constructor. The method
computePrice
is declared to be
private
because it is needed only by the constructor.
song1
is allocated and contains the null value.computePrice
is called; it returns a value which stored in the field
price
.song1
. The field
price
can be accessed to obtain the price of a song.Exercise Modify the class so that no song has a price greater than two currency units.
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.
Program: Constructor03.java
// Learning Object Constructor03
// overloading constructorsclass 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) {
name = n; seconds = s;
pricePerSecond = DEFAULT_PRICE; price = computePrice();
}
private double computePrice() { return seconds * pricePerSecond;
}}
public class Constructor03 {
public static void main(/*String[] args*/) {
Song song1 = new Song("Waterloo", 164, 0.01); Song song2 = new Song("Fernando", 253);
}}
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.
Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?