![]() |
![]() |
|
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; } |
magic number— the code gives the correct answer, but somebody looking at the code and didn't know where the 0.0222 came from could only conclude that we magically chose the correct number from thin air. (In this case, it came from actually measuring some disk-usage for a real iTunes collection; it works out to 1.3MB/min. 1 MB/min is a reasonable estimate to keep in your head.)
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
mean?
means "this will never change". (We'll see soon, that regular fields can change.)final
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.)
, that's actually2 turned in to"hello"
. We can double-click on the small red box in BlueJ to see its fields! (Note: they're private. We'll soon learn about both arrays, and objects-whose-fields-are-other-objects. The field of typenew String("hello")
wrapsaround a single
new Integer(17) // create an object of the 'wrapper' class Integer. |
Math.PI Integer.MAX_VALUE Double.POSITIVE_INFINITY |
(So it has become block-comment already after two characters; java itself doesn't care about third character (since it's inside a comment).)/**
/** 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.
five times, it only calls a"hello"
This page licensed CC-BY 4.0 Ian Barland Page last generated | Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |