|
home—info—lects—labs—exams—hws
tutor/PIs—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 boolean fitsOnDisk( Song aSong, double freeSpace ) { if (aSong.length/60 <= freeSpace) { return true; } else { return false; } } |
static boolean fitsOnDisk( Song aSong, double freeSpace ) { double MB_PER_SEC = 1.0/60.0; if (aSong.length*MB_PER_SEC <= freeSpace) { … |
Solution: Make the named constant a field — but a static field!
class Song extends Object120 { // fields: String title; String artist; double length; boolean isCopyrighted; // a static field: static double MB_PER_SEC = 1.0/60.0; // 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 does the adjective “
A static field is associated with the class,
and not with individual objects.
(Display/demo using BlueJ:
make two objects and inspect them,
and right-click on the class and choose 'inspect'.)
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 in a few weeks. 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 |
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—Object120 + its docs—java.lang docs—java.util docs
©2010, Ian Barland, Radford University Last modified 2010.Oct.10 (Sun) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |