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
.
- Two objects of class Song are instantiated and references to them
are assigned to the variables
song1
andsong2
. - The method
computePrice
is called on the object referenced bysong1
. In Jeliot this is visualized by an arrow to the object placed in theExpression Evaluation Area
followed by a period and the method name and parameters. - An activation record is allocated containing two formal parameters:
this
is initialized by the implicit reference andpricePerSecond
is initialized from the actual parameter. - The local variable
price
is declared and initialized by the expression calculated from the formal parameterpricePerSecond
and the field of the objectseconds
that is implicitly accessed throughthis
. - The method
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 isthis
and it is used to initialize the implicit formal parameterthis
of the methoddiscount
. - The activation record for
computePrice
is deallocated and the value returned is stored in the variableprice1
. - A second call to the method is executed exactly the same way,
except that it is called
on the object referenced by
song2
. - The values of
price1
andprice2
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.
- This program is a modification of the previous one: instead of comparing
s
with 300 in the methoddiscount
, it is compared with the value returned by the methodlevel
. It is impossible to tell from the calls alone todiscount
andlevel
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.