<< Chapter < Page | Chapter >> Page > |
Program: Constructor01B.java
// Learning Object Constructor01B
// what are constructors for?class Song {
String name; int seconds;
double pricePerSecond;
Song() { name = "Waterloo";
seconds = 164; pricePerSecond = 0.01;
}
public double computePrice() { return seconds * pricePerSecond;
}}
public class Constructor01B {
public static void main(/*String[] args*/) {
Song song1 = new Song(); double price = song1.computePrice();
}}
This program is the same as the previous one except that the assignment of nondefault values to the fields of the object is moved to an explicit constructor.
song1
is allocated and contains the null value.song1
.song1
is used to call the method
computePrice
on the object; the method computes and returns the price,
which is assigned to the variable
price
.
Exercise Add the creation of a second object
song2
to the
program and verify that it is initialized to the same values.
Concept Of course, it is highly unlikely that all objects created from a class will be initialized with the same values. A constructor can have formal parameters like any other method and is called with actual parameters.
Program: Constructor01C.java
// Learning Object Constructor01C
// what are constructors for?class Song {
String name; int seconds;
double pricePerSecond;
Song(String n, int s, double p) { name = n;
seconds = s; pricePerSecond = p;
}
public double computePrice() { return seconds * pricePerSecond;
}}
public class Constructor01C {
public static void main(/*String[] args*/) {
Song song1 = new Song("Waterloo", 164, 0.01); double price = song1.computePrice();
}}
This program is the same as the previous one except that the constructor has formal parameters and the actual parameters passed to the constructor are assigned to the fields of the object.
song1
is allocated and contains the null value.song1
.song1
is used to call the method
computePrice
on the object; the method computes and returns the price,
which is assigned to the variable
price
.
Exercise Modify the class so that the second parameter passes
the number of minutes; the value of the field
seconds
will have
to be computed in the constructor.
Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?