1 OO Design with Inheritance C Sc 335 Rick Mercer.

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Chapter 10 Inheritance, Polymorphism, and Scope. 2 Knowledge Goals Understand the hierarchical nature of classes in object-oriented programming Understand.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Object-oriented Programming Concepts
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Abstract Classes and Interfaces
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritance using Java
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Polymorphism & Interfaces
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
What is inheritance? It is the ability to create a new class from an existing class.
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.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
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)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
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.
03/10/14 Inheritance-2.
OO Design with Inheritance
OO Design with Inheritance
OO Design with Inheritance
OO Design with Inheritance
Presentation transcript:

1 OO Design with Inheritance C Sc 335 Rick Mercer

2 Justification and Outline I introduce inheritance different than most books that just show the mechanics and examples like the Bicycle hierarchy from SunBicycle I start with a reason to use inheritance –Show the objects found for a Library System –Recognize when to use inheritance –Build an inheritance hierarchy –Design Guidelines related to inheritance –See another use of polymorphism

3 The 3 Pillars of OOP&D Object-Oriented Programming –Encapsulation Hide details in a class, provide methods –Polymorphism Same name, different behavior, based on type –Inheritance Capture common attributes and behaviors in a base class and extend it for different types

4 Object-Oriented Technology OOT began with Simula 67 –developed in Norway –acronym for simulation language Why this “new” language (in the 60s)? –to build accurate models for the description and simulation of complex man-machine systems The modularization occurs at the physical object level (not at a procedural level)

5 The Beginnings Simula 67 was designed for system simulation (in Norway by Kristen Nygaard and Ole-Johan Dahl) –Caller and called subprogram had equal relationship –First notion of objects including class/instance distinctions –Ability to put code inside an instance to be executed –The class concept was first used here Kristen Nygaard Kristen Nygaard invented inheritance –Kristen Won the Turing award for 2002

6 One way to Start OOA and D Identify candidate objects that model (shape) the system as a natural and sensible set of abstractions Determine main responsibility of each –what an instance of the class must be able to do and what is should remember This is part of Responsibility Driven Design ala Rebecca Wirfs-Brocks

7 System Specification The college library has requested a system that supports a small set of library operations. The librarian allows a student to borrow certain items, return those borrowed items, and pay fees. Late fees and due dates have been established at the following rates: Late feeLength of Borrow Books $0.50 per day 14 days Video tapes$5.00 plus 1.50 each additional day2 days CDs$2.50 per day 7 days The due date is set when the borrowed item is checked out. A student with three (3) borrowed items, one late item, or late fees greater than $25.00 may not borrow anything new.

8 Identify candidate objects Candidate objects that model a solution with main responsibility. The model (no GUIs, events, networking) –Librarian: Coordinates activities –Student, renamed Borrower –Book: Knows due date, late fees, Borrower, checkin... –Video: Knows due date, late fees, Borrower, checkin... –CD: Know due date, late fees, Borrower, checkin... –Three borrowed books: A collection of the things that can be borrowed, name it LendableList –BorrowList: maintains all possible borrowers

9 A Sketch drawn pre-UML

10 What do Books, Videos, and CDs have in common? Common responsibilities (methods and data): –know call number, borrower, availability –can be borrowed –can be returned Differences: –compute due date –compute late fee –may have additional state Books have an author, CDs an artist

11 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

12 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

13 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

14 Examples of inheritance in Java You've seen HAS-A relationships: –A Song HAS-A most recent date played Inheritance models IS-A relationships: –MyFrame extends JFrame that makes MyFrame a JFrame with additional methods and listeners for a specific application

15 A Few Examples of Inheritance All Exceptions extend Exception: Many classes extend the Component class –JButton IS-A Component –JTextField IS-A Component A GregorianCalender IS-A Calendar Vector and ArrayList extend AbstractList DuplicateCardException IS-A RuntimeException JukeboxGUI IS-A JFrame

16 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 }

17 Some common data fields Every class in the hierarchy ended with these private instance variables in class Lendable: –Subclasses can not directly reference these private String callNumber; private String title; private boolean availability; private String borrowerID; private DayCounter dueDate;

18 Lendable's constructor Constructor needs a callNumber and title since it seems that all Lendables will need both The actual values will later come from the subclasses constructor public Lendable(String callNumber, String initTitle) { this.callNumber = callNumber; title = initTitle; borrowerID = null; dueDate = null; availability = true; }

19 Common Behavior public String getCallNumber() { return callNumber; } public String getTitle() { return title; } public boolean isAvailable() { return availability; } public DayCounter getDueDate { return dueDate; }

20 Common Behavior continued public int daysLate() { int result = 0; if (!isAvailable()) { DayCounter today = new DayCounter(); result = dueDate.daysFrom(today); } return result; } public boolean isOverdue() { if (this.isAvailable()) return false; return daysLate() > 0; }

21 Common Behavior continued public boolean checkSelfIn() { if (this.isAvailable()) { return false; } else { dueDate = null; availability = true; return true; }

22 Abstract methods –Subclasses differ: setDueDate getLateFee declare the appropriate methods abstract, to force sub-classes to implement them in their own appropriate ways public abstract class Lendable { // We Don't really borrow a Lendable, // but you borrow a book // Nor do you or eat a Fruit // but you can Eat a Peach // Subclasses must implement these two methods abstract public void checkSelfOut(String ID); abstract public double getLateFee(); } // Done with Lendable for now

23 What can subclass do? General form for inheriting a Java class: public class subclass extends superclass { may add a constructor may override methods in the superclass may add additional constructors may add class constants may add instance variables may add new methods }

24 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 super(callNum, title) –if used, super must be the first message in the constructor of the derived classes

25 Book extends Lendable public class Book extends Lendable { // Class constants public static final int DAYS_TO_BORROW_BOOK = 14; public static final double BOOK_LATE_DAY_FEE = 0.50; // Instance variable added private String my_author; public Book(String callNumber, String title, String author) { super(callNumber, title); my_author = author; }

26 Complete both abstract methods public void checkSelfOut(String borrowerID) { // Record who is borrowing this Lendable setBorrowerID(borrowerID); // Set the new due date by the correct days DayCounter due = new DayCounter(); due.adjustDaysBy(Book.DAYS_TO_BORROW_BOOK); setDueDate(due); // Mark this Lendable as no longer available setAvailability(false); }

27 Complete both abstract methods public double getLateFee() { if (this.isAvailable()) return 0.00; else { int daysOverdue = this.daysLate(); if (daysOverdue > 0) // The book is overdue. return daysOverdue * Book.BOOK_LATE_DAY_FEE; else return 0.00; // The due date is in the future } }

28 Book IS-A Lendable, cast public void testGetters() { Lendable 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", ((Book) aBook).getAuthor()); assertEquals(0.00, aBook.getLateFee(), 1e-12); assertTrue(aBook.isAvailable()); aBook.checkSelfOut("Rick"); assertFalse(aBook.isAvailable()); }

29

30 Lendables in a List ArrayList collection = new ArrayList<>(); collection.add(new Book("QA76.1", "C++", "Jo")); Video aVideo = new Video("VIDEO1", "The Matrix"); collection.add(aVideo); Lendable aLendable = collection.get(0); assertEquals("C++", aLendable.getTitle()); assertEquals("QA76.1", aLendable.getCallNumber()); aLendable = collection.get(1); assertEquals("The Matrix", aLendable.getTitle()); assertEquals("VIDEO1", aLendable.getCallNumber());

31 Lendables in a List collection.get(0).checkSelfOut("Kim"); collection.get(1).checkSelfOut("Kim"); for (Lendable thingToBorrow : collection) { System.out.println("Due date: " + thingToBorrow.getDueDate()); System.out.println("Days late: " + thingToBorrow.daysLate()); } Output: Due date: 2014/10/27 Days late: -14 Due date: 2014/10/15 Days late: -2

32 Design Issues So far, good design for the following reasons: –subclasses can't change the private variables of the superclass, even though the subclass has them –super used to avoid a bunch of setter methods in Lendable for subclasses to modify their variables –the common behavior is in the superclass the same thing is done for all subclasses –We'll get a polymorphic checkSelfOut and getLateFee messages

33 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

Java’s 4 Access Modes Public: known wherever the Object is declared –Modifier public Private: known only in the class –Modifier private Package: everywhere within the package No modifier: Particular to Java Protected …. 34

35 Protected The protected access mode means that only subclasses can reference them –Subclasses can directly reference all public & protected elements –Subclass inherit private methods and instance variables, but they can not be directly referenced Information hiding This limits method calls to subclasses –Somewhat private Some people use protected instance variables, we won’t