![]() |
![]() |
|
They're just regular functions, but Java sure tries to obscure that with special rules:
as part of the function's name.new␣
Song2( String t, String a, double l, boolean isC ) { // Song2 this = /* a Song2 object w/ all fields "zero-ish" */; // implicit -- don't write it! this.title = t; this.artist = a; this.length = l; this.isCopyrighted = isC; // return this; // implicit -- don't write it! } |
We will copy/rename
1 class Song2 extends Object120 { 2 String title; 3 String artist; 4 double length; // running time, in s. 5 boolean isCopyrighted; 6 7 8 // the "constructor": 9 Song2( String t, String a, double l, boolean isC ) { 10 // Song2 this = /* a Song2 object w/ all fields "zero-ish" */; // implicit -- don't write it! 11 this.title = t; 12 this.artist = a; 13 this.length = l; 14 this.isCopyrighted = isC; 15 // return this; // implicit -- don't write it! 16 } 17 18 19 /** return whether `s` can be stored using `space` disk-space. 20 * @param s the song to consider 21 * @param space the amount of available space it has to fit into, in B. 22 */ 23 static boolean willFit( Song2 s, int space ) { 24 return (s.length/60)*3.0*Math.pow(2,20) <= space; 25 } 26 27 /** return whether one song is shorter than another. 28 * @return whether s1 is shorter than s2. 29 */ 30 static boolean isShorter( Song2 s1, Song2 s2 ) { 31 return (s1.length < s2.length); 32 } 33 34 /** return a remix of a song. 35 * @return `orig` remixed by D.J. `dj`, who added `newMaterialLength` seconds of ill beatz. 36 */ 37 static Song2 remix( Song2 orig, String dj, double newMaterialLength ) { 38 return new Song2( orig.title + " (" + dj + " remix)", 39 orig.artist + " vs " + dj, 40 orig.length + newMaterialLength, 41 false ); 42 } 43 44 45 46 static void testAll() { 47 // some examples of Song2 objects: 48 Song2 s1 = new Song2("Old Town Road", "Lil Nas X", 120, true); 49 Song2 s2 = new Song2("Ring Ring", "Abba", 180, true); 50 Song2 s2a = new Song2("Ring Ring", "Abba", 180, true); 51 52 53 printTestMsg("remix"); 54 assertEquals( new Song2( "Old Town Road (ibarland remix)", 55 "Lil Nas X vs ibarland", 56 150, 57 false ), 58 remix(s1, "ibarland", 30 ) ); 59 assertEquals( new Song2("Ring Ring (saltman remix)", "Abba vs saltman", 180, false), 60 remix(s2, "saltman", 0 ) ); 61 printTestSummary(); 62 } 63 64 public static void main( String[] args ) { testAll(); } 65 66 } |
This page licensed CC-BY 4.0 Ian Barland Page last generated | Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |