<< Chapter < Page | Chapter >> Page > |
This program computes the cost of a song as the product of its length
in seconds and the price per second. A discount is appliedto “long” songs. A class
Song
is defined
to encapsulate the field
seconds
and the methods
computePrice
and
discount
.
song1
and
song2
.computePrice
is called
on the object referenced by
song1
. In Jeliot this is visualized by an arrow to the object
placed in the
Expression Evaluation Area
followed by a period and
the method name and parameters.this
is initialized by the implicit reference and
pricePerSecond
is initialized from the actual parameter.price
is declared and initialized by the
expression calculated from the formal parameter
pricePerSecond
and
the field of the object
seconds
that is implicitly accessed through
this
.discount
,
declared in the same class, is invoked and returns a boolean value.A new activation is allocated for this method and deallocated when it terminates.
The implicit actual parameter is
this
and it is used to initialize the
implicit formal parameter
this
of the method
discount
.computePrice
is deallocated
and the value returned is stored in the variable
price1
.song2
.price1
and
price2
are printed.
Exercise Modify the program so that discount does not use the explicit
parameter
s
.
Program: Method06B.java
// Learning Object Method06B
// calling a method on the same objectclass Song {
int seconds;
Song(int s) { seconds = s;
}
static int level(int n) { return n * 100;
}
boolean discount(int s) { return s > level(3);
}
double computePrice(double pricePerSecond) { double price = seconds * pricePerSecond;
if (discount(seconds)) price = price * 0.9;
return price; }
}
public class Method06B { public static void main(/* String[] args */) { Song song1 = new Song(164);
Song song2 = new Song(403); double price1 = song1.computePrice(0.01);
double price2 = song2.computePrice(0.01); System.out.println(price1);
System.out.println(price2); }
}
Given a call to a method
m2
within a method
m1
:
void m1() {
m2();}
it is impossible to tell from the call if m2 is being implicitly called on the same object or if it is a static method defined in the class.
s
with 300 in the method
discount
, it is compared with
the value returned by the method
level
. It is impossible to tell
from the calls alone to
discount
and
level
that the first is
a call on an object while the second is a call to a static method.
Exercise Modify the calls to
discount
and
level
so that it is immediately apparent which is definitely a call on an object and which
is definitely a call to a static method.
Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?