// An example of using Inheritance, Overloading and polymorphism /** Our good old book class */ class Book { protected String title; /* notice that these are */ protected int npages; /* now protected, not private */ public Book() { // Default constructor title = "No title"; npages = 0; } /** A second constructor */ public Book(String booktitle, int pages) { title = booktitle; npages = pages; } /** A public method */ public void Read(int pagestart, int pageend) { if (pageend < npages) { System.out.println("Reading "+ title + " from page " + pagestart + " to " + pageend); } else { System.out.println("Give me another book!"); } } } /** The first subclass - hardly anything extra, just to show things */ class ComicBook extends Book { public ComicBook(String booktitle, int pages) { title = booktitle; /* title is not in this class - INHERITED */ npages = pages; /* likewise */ } } class TextBook extends Book { private String Course; public TextBook(String booktitle, int pages, String incourse) { super(booktitle, pages); Course = incourse; } public void Read(int pagestart, int pageend) { System.out.println(Course + "has a very dull textbook!"); } } public class BookReader { public static void main(String[] args) { // create a new Comic Book ComicBook favoriteComic = new ComicBook("Yukon Ho!", 85); favoriteComic.Read(75, 95); // Read is not in ComicBook, still works! // *** Inheritance *** // create a new text book, but assign it to a variable of tyep Book! // *** Polymorphism *** Book a201Text = new TextBook("CCJ", 625, "A201"); a201Text.Read(475, 525); // This time use the overloaded Read // method in Textbook. // *** Overloading *** } }