// `record` requires java14: // compile: `javac --enable-preview --source 14 Book2.java` // run: `java --enable-preview Book` // or: `jshell --enable-preview` then `/open Book2.java` // record Book(String title, String author, int numPages, boolean isCopyrighted) { /* ( Template for book-handling functions: ) ... funcForBook( /* Book this * / ) { ... this.title ... this.author ... this.numPages ... this.isCopyrighted } */ /** @return The amount of time it takes the average reader to read a book (in minutes) */ double readingTime( /* Book this */ ) { return 2 * this.numPages; } @Override public String toString( /* Book this */ ) { return this.title + ", by " + this.author + " (" + this.numPages + "pp)" + (this.isCopyrighted ? " ©" : "" ); } /** @return a book just like `a-book`, but with bigger text (hence, more pages). */ Book enbiggen( /* Book this */ ) { return new Book( this.title, this.author, 2*this.numPages, this.isCopyrighted ); } /** @return a brand new book, based on an original. * The result's authoor will be the original author & the `newAuthor`, * and the result has `numNewPages` pages added to the original. */ Book deriveFrom( /* Book this, */ String newAuthor, int numNewPages ) { return new Book( "Son of " + this.title, this.author + " & " + newAuthor, this.numPages + numNewPages, false ); } /* All code has to be inside a method in Java, so we'll stick our unit-tests in here. */ static void testAll() { Book b0, b1; b1 = new Book( "The Cat in the Hat", "Seuss", 37, true ); b0 = new Book( "The Soul of Wit", "Barland", 0, false ); assert (new Book( "The Cat in the Hat", "Seuss", 37, true )).readingTime() == 74.0; assert b0.readingTime() == 0; assert b1.enbiggen().equals(new Book( "The Cat in the Hat", "Seuss", 74, true )); assert (new Book( "The Bat in the Mat", "Streuss", 1, true )).enbiggen() .equals(new Book( "The Bat in the Mat", "Streuss", 2, true )); assert b0.enbiggen().equals(b0); assert b1.deriveFrom("Barland", 10) .equals( new Book( "Son of The Cat in the Hat" , "Seuss & Barland" , 47 , false ) ); assert b0.deriveFrom("Banksie", 99) .equals( new Book( "Son of The Soul of Wit" , "Barland & Banksie" , 99 , false ) ); assert b0.equals(b0); assert !b0.equals(b1); assert b1.equals( new Book( "The Cat in the Hat", "Seuss", 37, true ) ); assert b0.hashCode() == b0.hashCode(); assert b1.hashCode() == new Book( "The Cat in the Hat", "Seuss", 37, true ).hashCode(); assert b1.toStringDebug().equals( "new Book( \"The Cat in the Hat\", \"Seuss\", 37, true )" ); } /** Just run our unit tests. Be sure to run `java` with `--assertionsEnabled` (or, `-ea`). */ public static void main( String... __ ) { testAll(); // Alternately, we could just stick the tests directly into `main` here, that's fine too. } }