210 likes | 232 Vues
Explore the appropriateness of inheritance in object-oriented design, creating an inheritance hierarchy, defining common behaviors, and implementing polymorphic messages effectively.
E N D
OO Design with Inheritance C Sc 335 Rick Mercer
When is inheritance appropriate? • Object-Oriented Design Heuristic: If two or more classes have common data and behavior, then those classes should inherit from a common base class that captures those data and methods review
An inheritance hierarchy The abstract class never instantiated Lendable is also known as the base class or superclass Lendable is shown to abstract (in italic) Book, CD, and Video are concrete subclasses review
Why not have just one class? • Some of the behavior differs • Determine due date (2, 7, or 14 days) • Compute late fee not always daysLate * dayLateFee • Data differs • books have ISBNs and videos may have studio name • Inheritance • allows you to share implementations • allows one change in a common method to affect all • allows other Lendables to be added later more easily review
Designing An Inheritance Hierarchy • Start with an abstract class to define common-alities and differences (abstract methods) publicabstract class Lendable { private instance variables constructor(s) methods that Lendable implements when the behavior is common to all of its subclasses (what is common) abstract methods the subclasses must implement that to represent what varies } review
Some common data fields • Every class in the hierarchy ended with these instance variables in class Lendable: • We'll need some getters and setters, even in subclasses such as Book, Video, ... private String callNumber; private String title; private boolean availability; private String borrowerID; private DayCounterdueDate; new
Lendable's constructor • Constructor needs a callNumber and title since it seems that all Lendables will need both • The actual values will come from subclasses public abstract class Lendable { public Lendable(String callNumber, String initTitle) { callNumber = callNumber; // from subclass title = initTitle; // from subclass // Initialize others in a special way borrowerID = null; dueDate = null; availability = true; }
Common Behavior public String getCallNumber() { return callNumber; } public String getTitle() { return title; } public boolean isAvailable() { return availability; } public DayCounter getDueDate() { return dueDate; }
Common Behavior continued public intdaysLate() { // return a positive if dueDate is before today DayCounter today = new DayCounter(); return dueDate.daysFrom(today); } public booleanisOverdue() { if(this.isAvailable()) return false; // not even checked out // Or check to see if this Lendable is overdue // Return true if today is greater than // the due date for this Lendable return daysLate() > 0; }
Common Behavior continued public booleancheckSelfIn() { if(this.isAvailable()) return false; else { // Adjust state so this is checked out dueDate = null; availability = true; return true; } }
Need setters for subclasses and testing public void setDueDate(DayCounter d) { dueDate = d; } public void setAvailability(boolean tOrF) { availability = tOrF; } public void setBorrowerID(String ID) { this.borrowerID = ID; }
Behavior that differs • Wanted: polymorphic messages so different types get different behavior • The base class can require that all subclasses implement certain methods • Make the method abstract (like in an interface) • These are the behaviors that differ checkSelfOut getLateFee
Abstract Methods • Declare the appropriate methods abstract • use the headings with ; as in an interface • This forces subclasses to implement them in their own appropriate ways public abstract class Lendable { // Don't really borrow a Lendable, you bo ... // Subclass must implement these two methods public abstractvoid checkSelfOut(String ID); public abstractdouble getLateFee(); }// Done with Lendable for now
What can a subclass do? • General form for inheriting a Java class: public class subclass extends superclass { // this subclass inherits all instance // variables and methods of superclass may add class constants may add instance variables may add 1 to many constructors may add public, private, packed and protected methods may override methods in the superclass (or its superclass) }
The Constructor and Super • A subclass typically defines its constructor. If not • You will still get a default constructor with 0 parameters that automatically calls the base class constructor • Constructors in a subclass often call the superclass constructor to initialize the objects • Access superclass with the keyword super • can pass along arguments with super super(callNum, title) • if used, super must be the first message in the constructor of the derived classes
Book extends Lendable public class Book extends Lendable { // Adding two class constants public static final int DAYS_TO_BORROW_BOOK = 14; public static final double BOOK_LATE_DAY_FEE = 0.50; // Add an instance variable private String author; public Book(String callNum, String title, String author){ // Call the superclass constructor super(callNum, title); this.author = author; } // Add a method public String getAuthor() { return author; } }
Implement both required methods /** * Modify the state of this object so it is borrowed. * @param borrowerID * The String identification of the borrower. */ public void checkSelfOut(String borrowerID) { // Record who is borrowing this Lendable setBorrowerID(borrowerID); // Set the new due date by the correct number of days passed as // an argument by the particular class that extends Lendable DayCounter due = new DayCounter(); due.adjustDaysBy(Book.DAYS_TO_BORROW_BOOK); setDueDate(due); // Mark this Lendable as no longer available to be borrowed setAvailability(false); }
getLateFee differs among the Lendable subclasses @Overridepublic double getLateFee() { if(this.isAvailable()) // Not even checked out! return 0.00; else { // A positive daysLate means due date has passed int daysOverdue = this.daysLate(); if(daysOverdue > 0) // This Lendable is overdue return daysOverdue * Book.BOOK_LATE_DAY_FEE; else return 0.00; // The due date has not passed } } }
A few assertions @Test public void testGetters() { // Show that Book has many methods via inheritance Book aBook = new Book("QA76.1", "C++", "Jo"); assertTrue(aBook.isAvailable()); assertFalse(aBook.isOverdue()); assertNull(aBook.getBorrowerID()); assertEquals("QA76.1", aBook.getCallNumber()); assertEquals("C++", aBook.getTitle()); assertEquals("Jo", aBook.getAuthor()); // Use the 2 methods that once were abstract and // now have concrete realizations assertEquals(0.00, aBook.getLateFee(), 1e-12); assertTrue(aBook.isAvailable()); aBook.checkSelfOut("Rick"); assertFalse(aBook.isAvailable()); }
Adding Other Subclasses • Extend Lendable • Optional: add class constants • days to borrow, late fee amounts • Add a constructor that passes along arguments to the constructor in Lendable (super) • Add the methods that Lendable requires of all sublclasses: use Override • checkSelfOut • getLateFee