![]() |
![]() |
|
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs
Song( String t, String a, double l, boolean c ) {
// Java declares a variable named `this` and
// initializes it to a new, unfilled object.
this.title = t;
this.artist = a;
this.length = l;
this.isCopyrighted = c;
}
|
We previously wrote a function with
static double diskSpaceRequired( Song aSong ) {
return aSong.length* 0.0222;
}
|
static boolean fitsOnDisk( Song aSong, double freeSpace ) {
double MB_PER_SEC = 0.0222;
return (aSong.length*MB_PER_SEC);
|
Solution: Make the named constant a field — but a static final field!
class Song extends Object120 {
// fields:
String title;
String artist;
double length;
boolean isCopyrighted;
// a static field:
static final double MB_PER_SEC = 0.0222;
// N.B. You *must* declare and init a static field on the same line!
…
static boolean fitsOnDisk( Song aSong, double freeSpace ) {
if (aSong.length * MB_PER_SEC <= freeSpace) {
…
}
}
|
So: what do the adjectives “
So if we create fifty
In fact, even if we have zero
(This is also true of static functions: a non-static function is associated with a particular object. That's called object-oriented programming, and we'll start doing that next week. But for now, we'll keep all our functions static, and even though we're using objects we're not yet doing actual object-oriented programming.)
new Integer(17) // create an object of the 'wrapper' class Integer.
|
Math.PI
Integer.MAX_VALUE
Double.POSITIVE_INFINITY
|
/** Return an estimate of the space required to store the mp3 for a Song.
* @param myTune The song to estimate the size of.
* @return an estimate of the space required to store the mp3 for a `myTune`, in MB.
*/
static double diskSpaceUsed( Song myTune ) {
return myTune.length * 0.0222;
}
|
Note: the comments should describe what the function does, and not how the function goes about its task. People calling your function don't care about how it works — just what it will return.
1 Note how we're declaring and initializing on the same line; we'll need that fact in a moment. ↩
2Well, actually Java tries to re-use
literally defined
3
Why on earth would you ever want to treat
an
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs
| ©2012, Ian Barland, Radford University Last modified 2012.Oct.08 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarland |
![]() |