OO Design with Inheritance

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Inheritance using Java
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
These materials where developed by Martin Schray. Please feel free to use and modify them for non-commercial purposes. If you find them useful or would.
AP Computer Science A – Healdsburg High School 1 Interfaces, Abstract Classes and the DanceStudio - Similarities and Differences between Abstact Classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 OO Design with Inheritance C Sc 335 Rick Mercer.
Object Oriented Programming
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 OO Design with Inheritance C Sc 335 Rick Mercer.
16-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Sections Inheritance and Abstract Classes
Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object Oriented Programming
CSC 143 Inheritance.
Inheritance Basics Programming with Inheritance
null, true, and false are also reserved.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Advanced Programming Behnam Hatami Fall 2017.
OO Design with Inheritance
Advanced Java Programming
Computer Programming with JAVA
Inheritance Inheritance is a fundamental Object Oriented concept
Java Programming, Second Edition
Java Inheritance.
Simple Classes in Java CSCI 392 Classes – Part 1.
Class Inheritance Concept of Inheritance Java keywords
Chapter 9 Carrano Chapter 10 Small Java
Chapter 14 Abstract Classes and Interfaces
CIS 199 Final Review.
Chapter 8 Class Inheritance and Interfaces
Chapter 8 Inheritance Part 2.
Final and Abstract Classes
OO Design with Inheritance
OO Design with Inheritance
Chengyu Sun California State University, Los Angeles
Presentation transcript:

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) public abstract 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 DayCounter dueDate; 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 int daysLate() { // return a positive if dueDate is before today DayCounter today = new DayCounter(); return dueDate.daysFrom(today); } public boolean isOverdue() { 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 boolean checkSelfIn() { 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 abstract void checkSelfOut(String ID); public abstract double 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 @Override public 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); 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