<< Chapter < Page | Chapter >> Page > |
Exercise Modify the class to include a constructor with one parameter, the name, and with a default song length of three minutes. Can this constructor call the two-parameter constructor which in turn calls the three-parameter constructor? Can a constructor call two other constructors, one after another?
Concept When no constructor is explicitly written in a class, a default implicit constructor with no parameters exists; this constructor does nothing. If, however, one or more explicit constructors are given, there is no longer a constructor with no parameters. Should you want one, you have to write it explicitly.
Program: Constructor05.java
// Learning Object Constructor05
// explicit default 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();
}
Song() { this("No song", 0, 0.0);
}
private double computePrice() { return seconds * pricePerSecond;
}}
public class Constructor05 {
public static void main(/*String[] args*/) {
Song song1 = new Song(); }
}
This program includes an explicit constructor with no parameters that calls the constructor with three parameters to perform initialization.
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
.Exercise Modify the class so that the constructor without parameters obtains initial values from the input.
Concept Constructors are
not inherited. You must
explicitly define a constructor for a subclass (with or withoutparameters). As its first statement, the constructor for the subclass must
call a constructor for the superclass using the method
super
.
Program: Constructor06A.java
// Learning Object Constructor06A
// constructors for subclassesclass 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;
}}
class DiscountSong extends Song {
double discount;
DiscountSong(String n, int s, double p, double d) { super(n, s, p);
discount = d; }
private double computePrice() {
return seconds * pricePerSecond * discount; }
}
public class Constructor06A { public static void main(/*String[] args*/) { DiscountSong song1 = new DiscountSong("Waterloo", 164, 0.01, 0.8);
double price = song1.price; }
}
Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?