CSE 331 Software Design & Implementation
|
|
- Sandra Boone
- 5 years ago
- Views:
Transcription
1 CSE 331 Software Design & Implementation Kevin Zatloukal Fall 2017 Subtypes and Subclasses (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock)
2 What is subtyping? Sometimes every B is an A examples in a library database: every book is a library holding every CD is a library holding A B LibraryHolding Book CD For subtyping, B is a subtype of A means: every object that satisfies the rules for a B also satisfies the rules for an A (B is a strengthening of A) Circle Shape Rhombus Goal: code written using A's spec operates correctly if given a B plus: clarify design, share tests, (sometimes) share code 2
3 Subtypes are substitutable Subtypes are substitutable for supertypes Liskov substitution principle instances of subtype won't surprise client by failing to satisfy the supertype's specification instances of subtype won't surprise client with more expectations than the supertype's specification We say B is a true subtype of A if B has a stronger specification than A (or is equally strong) this is not the same as a Java subtype Java subtypes that are not true subtypes: confusing & dangerous but unfortunately common L Java allows casting sub- to supertypes assuming true subtypes 3
4 Subtyping vs. subclassing Substitution (subtype) is a matter of specifications B is a subtype of A iff an object of B can masquerade as an object of A in any context B is a subtype if its spec is is a strengthening of A s spec Inheritance (subclass) is a matter of implementations factor out repeated code to create a new class, write only the differences Java purposely merges these notions for classes: every subclass is a Java subtype but not necessarily a true subtype (though Java casting rules assume true subtypes) 4
5 Inheritance makes adding functionality easy Suppose we run a web store with a class for products class Product { private String title; private String description; private int price; // in cents public int getprice() { return price; public int gettax() { return (int)(getprice() * 0.086);... and we need a class for products that are on sale 5
6 Copy and Paste class SaleProduct { private String title; private String description; private int price; // in cents private float factor; public int getprice() { return (int)(price*factor); public int gettax() { return (int)(getprice() * 0.086); Not a good choice. Why? (hint: properties of high quality code) 6
7 Inheritance makes small extensions small Better: class SaleProduct extends Product { private float factor; public int getprice() { return (int)(super.getprice()*factor); 7
8 Benefits of subclassing & inheritance Don t repeat unchanged fields and methods in implementation: simpler maintenance: fix bugs once (changeability) in specification: clients who understand the superclass specification need only study novel parts of the subclass (readability) differences not buried under mass of similarities modularity: can ignore private fields and methods of superclass (if properly designed) Ability to substitute new implementations (modularity) no client code changes required to use new subclasses 8
9 Subclassing can be misused Poor design can produce subclasses that depend on many implementation details of superclasses super- and sub-classes are often highly interdependent Changes in superclasses can break subclasses fragile base class problem Subtyping and implementation inheritance are orthogonal! subclassing gives you both sometimes you want just one. instead use: interfaces: subtyping without inheritance composition: use implementation without subtyping can seem less convenient, but often better long-term 9
10 Is every square a rectangle? interface Rectangle { // effects: fits shape to given size: // this post.width = w, this post.height = h void setsize(int w, int h); interface Square extends Rectangle { Which is the best option for Square s setsize specification? 1. // requires: w = h // effects: fits shape to given size void setsize(int w, int h); 2.// effects: sets all edges to given size void setsize(int edgelength); 3.// effects: sets this.width and this.height to w void setsize(int w, int h); 4. // effects: fits shape to given size // throws BadSizeException if w!= h void setsize(int w, int h) throws BadSizeException; 10
11 Square, Rectangle Unrelated (Subtypes) Square is not a (true subtype of) Rectangle: Rectangles are expected to have a width and height that can be mutated independently Squares violate that expectation, could surprise client Rectangle Square Rectangle is not a (true subtype of) Square: Squares are expected to have equal widths and heights Rectangles violate that expectation, could surprise client Square Subtyping is not always intuitive but it forces clear thinking and prevents errors Solutions: make them unrelated (or siblings) make them immutable! recovers elementary-school intuition Rectangle Shape Square Rectangle 11
12 Inappropriate subtyping in the JDK class Hashtable<K,V> { public void put(k key, V value){ public V get(k key){ // Keys and values are strings. class Properties extends Hashtable<Object,Object> { public void setproperty(string key, String val) { put(key,val); public String getproperty(string key) { return (String)get(key); Properties p = new Properties(); Hashtable tbl = p; tbl.put("one", 1); p.getproperty("one"); // crash! 12
13 Violation of rep invariant Properties class has a simple rep invariant: keys and values are Strings But client can treat Properties as a Hashtable can put in arbitrary content, break rep invariant From Javadoc: Because Properties inherits from Hashtable, the put and putall methods can be applied to a Properties object.... If the store or save method is called on a "compromised" Properties object that contains a non-string key or value, the call will fail. 13
14 Solution 1: Generics Bad choice: class Properties extends Hashtable<Object,Object> { Better choice: class Properties extends Hashtable<String,String> { JDK designers deliberately didn t do this. Why? backward-compatibility (Java didn t have generics before) (clients can become dependent even on bugs in your code ) 14
15 Solution 2: Composition class Properties { private Hashtable<Object, Object> hashtable; public void setproperty(string key, String value) { hashtable.put(key,value); public String getproperty(string key) { return (String) hashtable.get(key); Now, there are no get and put methods on Properties. (Best choice.) 15
16 Substitution principle for classes If B is a subtype of A, then a B can always be substituted for an A Any property guaranteed by A must be guaranteed by B anything provable about an A is provable about a B if an instance of subtype is treated purely as supertype (only supertype methods/fields used), then the result should be consistent with an object of the supertype being manipulated B is permitted to strengthen properties and add properties fine to add new methods (that preserve invariants) an overriding method must have a stronger (or equal) spec B is not permitted to weaken a spec no method removal no overriding method with a weaker spec 16
17 Substitution principle for methods Constraints on methods For each supertype method, subtype must have such a method (could be inherited or overridden) Each overridden method must strengthen (or match) the spec: ask nothing extra of client ( weaker precondition ) requires clause is at most as strict as in supertype s method guarantee at least as much ( stronger postcondition ) effects clause is at least as strict as in the supertype method no new entries in modifies clause promise more (or the same) in returns & throws clauses cannot change return values or switch between return and throws 17
18 Spec strengthening: argument/result types For method inputs: argument types in A s foo could be replaced with supertypes in B s foo places no extra demand on the clients but Java does not have such overriding A B LibraryHolding Book CD Shape For method outputs: result type of A s foo may be replaced by a subtype in B s foo no new exceptions (for values in the domain) existing exceptions can be replaced with subtypes (none of this violates what client can rely on) Circle Rhombus 18
19 Substitution exercise Suppose we have a method which, when given one product, recommends another: class Product { Product recommend(product ref); Which of these are possible forms of this method in SaleProduct (a true subtype of Product)? Product recommend(saleproduct ref); SaleProduct recommend(product ref); Product recommend(object ref); Product recommend(product ref) throws NoSaleException; // OK // OK, but in Java is overloading // bad // bad 19
20 Java subtyping Java types: defined by classes, interfaces, primitives Java subtyping stems from B extends A and B implements A declarations In a Java subtype, each corresponding method has: same argument types if different, then overloading unrelated methods compatible return types no additional declared exceptions 20
21 Java subtyping guarantees A variable s run-time type (i.e., the class of its run-time value) is a Java subtype of its declared type Object o = new Date(); // OK Date d = new Object(); // compile-time error If a variable of declared (compile-time) type T1 holds a reference to an object of actual (runtime) type T2, then T2 must be a Java subtype of T1 Corollaries: objects always have implementations of the methods specified by their declared type if all subtypes are true subtypes, then all objects meet the specification of their declared type Rules out a huge class of bugs 21
22 Java subtyping non-guarantees Java subtyping does not guarantee that overridden methods have smaller requires have smaller modifies have stronger postconditions Java only checks the return type not the postcondition could compute a completely different function have stronger effects have stronger throws (& only for the same cases as before) have no new unchecked exceptions 22
23 Inheritance can break encapsulation public class InstrumentedHashSet<E> extends HashSet<E> { private int addcount = 0; // count # insertions public InstrumentedHashSet(Collection<? extends E> c){ super(c); public boolean add(e o) { addcount++; return super.add(o); public boolean addall(collection<? extends E> c) { addcount += c.size(); return super.addall(c); public int getaddcount() { return addcount; 23
24 Dependence on implementation What does this code print? InstrumentedHashSet<String> s = new InstrumentedHashSet<String>(); System.out.println(s.getAddCount()); // 0 s.addall(arrays.aslist("cse", "331")); System.out.println(s.getAddCount()); // 4?! Answer depends on implementation of addall in HashSet different implementations may behave differently! if HashSet s addall calls add, then double-counting AbstractCollection s addall specification: adds all elements in the specified collection to this collection. does not specify whether it calls add Lesson: subclassing typically requires designing for inheritance self-calls is not the only example (more in future lectures) 24
25 Solutions 1. Change spec of HashSet indicate all self-calls less flexibility for implementers 2. Avoid spec ambiguity by avoiding self-calls a) re-implement methods such as addall more work b) use composition no longer a subtype (unless an interface is handy) bad for equality tests, callbacks, etc. 25
26 Solution 2b: composition Delegate public class InstrumentedHashSet<E> { private final HashSet<E> s = new HashSet<E>(); private int addcount = 0; public InstrumentedHashSet(Collection<? extends E> c){ this.addall(c); public boolean add(e o) { addcount++; return s.add(o); The implementation no longer matters public boolean addall(collection<? extends E> c) { addcount += c.size(); return s.addall(c); public int getaddcount() { return addcount; //... and every other method specified by HashSet<E> 26
27 Composition (wrappers, delegation) Implementation reuse without inheritance Easy to reason about. Self-calls are irrelevant Example of a wrapper class Works around badly-designed / badly-specified classes Disadvantages (may be worthwhile price to pay): does not preserve subtyping sometimes tedious to write may be hard to apply to equality tests, callbacks, etc. (although we already saw equals is hard for subclasses) 27
28 Composition does not preserve subtyping InstrumentedHashSet is not a HashSet anymore so can't easily substitute it It may be a true subtype of HashSet but Java doesn't know that! Java requires declared relationships not enough just to meet specification Interfaces to the rescue can declare that we implement interface Set if such an interface exists 28
29 normal Java style Interfaces reintroduce Java subtyping public class InstrumentedHashSet<E> implements Set<E> { private final Set<E> s = new HashSet<E>(); private int addcount = 0; public InstrumentedHashSet(Collection<? extends E> c){ this.addall(c); public boolean add(e o) { addcount++; What s bad about this constructor? return s.add(o); InstrumentedHashSet(Set<E> s) { this.s = s; public boolean addall(collection<? extends E> c) { addcount = s.size(); addcount += c.size(); return s.addall(c); public int getaddcount() { return addcount; //... and every other method specified by Set<E> 29
30 Interfaces and abstract classes Provide interfaces for your functionality client code to interfaces rather than concrete classes allows different implementations later facilitates composition, wrapper classes basis of lots of useful, clever techniques we'll see more of these later Consider also providing helper/template abstract classes makes writing new implementations much easier not necessary to use them to implement an interface, so retain freedom to create radically different implementations 30
31 Java library interface/class example // root interface of collection hierarchy interface Collection<E> // skeletal implementation of Collection<E> abstract class AbstractCollection<E> implements Collection<E> // type of all ordered collections interface List<E> extends Collection<E> // skeletal implementation of List<E> abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> // an old friend... class ArrayList<E> extends AbstractList<E> 31
32 Why interfaces instead of classes? Java design decisions: a class has exactly one superclass a class may implement multiple interfaces an interface may extend multiple interfaces Observation: multiple superclasses are difficult to use and to implement multiple interfaces, single superclass gets most of the benefit 32
33 Pluses and minuses of inheritance Inheritance is a powerful way to achieve code reuse Inheritance can break encapsulation a subclass may need to depend on unspecified details of the implementation of its superclass e.g., pattern of self-calls subclass may need to evolve in tandem with superclass okay when implementation of both is under control of the same programmer this is tricky to get right and is a source of subtle bugs Effective Java: either design for inheritance or else prohibit it favor composition (and interfaces) to inheritance 33
Lecture 11 Subtypes and Subclasses
CSE 331 Software Design and Implementation Lecture 11 Subtypes and Subclasses The Liskov Substitution Principle Let P(x) be a property provable about objects x of type T. Then P(y) should be true for objects
CSE 331 Software Design and Implementation. Lecture 12 Subtypes and Subclasses
CSE 331 Software Design and Implementation Lecture 12 Subtypes and Subclasses Zach Tatlock / Winter 2016 The Liskov Substitution Principle Let P(x) be a property provable about objects x of type T. Then
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 Subtypes and Subclasses (Slides bymike Ernst and David Notkin) 1 What is subtyping? Sometimes every B is an A A In a library database: every
Subtypes. CSE 331 University of Washington. Michael Ernst
Subtypes CSE 331 University of Washington Michael Ernst What is subtyping? Sometimes every B is an A In a library database: every book is a library holding every CD is a library holding Subtyping expresses
MIT EECS Michael Ernst Saman Amarasinghe
6.170 Lecture 9 Subtyping MIT EECS Michael Ernst Saman Amarasinghe 1 Outline Theory and Practice Why we like subclasses? True subtypes vs. Java subtypes Inheritance vs. Composition Substitution Principle
Announcements. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Intuition: Type Signature is a Specification.
Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle Announcements HW5 is due today, March 26, 2018 at 11:59:59 pm Exam 2 is next Thursday, March 29, 2018. Practice exam has been
Outline. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Benefits of Subtype Polymorphism. Subtype Polymorphism
Subtype, Subtyping vs. Subclassing, Liskov Substitution Principle Outline Subtype polymorphism Subtyping vs. subclassing Liskov Substitution Principle (LSP) Function subtyping Java subtyping Composition:
n HW5 out, due Tuesday October 30 th n Part 1: Questions on material we ll cover today n Part 2: BFS using your graph from HW4
Subtype, Subtyping vs. Subclassing, Liskov Substitution Principle Announcements n HW5 out, due Tuesday October 30 th n Part 1: Questions on material we ll cover today n Part 2: BFS using your graph from
Subtypes and Subclasses
Subtypes and Subclasses 6.170 Lecture 14 Fall - ocw.mit.edu Reading: Chapter 7 of Program Development in Java by Barbara Liskov 1 Subtypes We have used closed arrows in module dependence diagrams and object
Software Engineering CSC40232: SOFTWARE ENGINEERING. Guest Lecturer: Jin Guo SOLID Principles sarec.nd.edu/courses/se2017
CSC40232: SOFTWARE ENGINEERING Guest Lecturer: Jin Guo SOLID Principles sarec.nd.edu/courses/se2017 Department of Computer Science and Engineering http://www.kirkk.com/modularity/2009/12/solid-principles-of-class-design/
6.170 Recitation #5: Subtypes and Inheritance
6.170 Recitation #5: Subtypes and Inheritance What is true subtyping? True Subtyping is not exactly the same as Inheritance. As seen in an earlier lecture, class A is a true subtype of class B if and only
Credit is where Credit is Due. Lecture 28: OO Design Heuristics (Part 2) This Lecture. Last Lecture: OO Heuristics. Rules of Thumb
Credit is where Credit is Due Lecture 28: OO Design Heuristics (Part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2002 Some material for this lecture is taken
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Kevin Zatloukal Summer 2017 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) Overview Notions
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Hal Perkins Spring 2016 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) Object equality A
Java Object Oriented Design. CSC207 Fall 2014
Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code
Expected properties of equality
Object equality CSE 331 Software Design & Implementation Dan Grossman Spring 2015 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins) A simple idea??
Top Down Design vs. Modularization
6.170 Quiz Review Topics: 1. Decoupling 2. 3. AF & RI 4. Iteration Abstraction & Iterators 5. OMs and Invariants 6. Equality, Copying, Views 7. 8. Design Patterns 9. Subtyping 10. Case Studies Decomposition
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Kevin Zatloukal Fall 2017 Data Abstraction: Abstract Data Types (ADTs) (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) Outline
Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004
Type Hierarchy Comp-303 : Programming Techniques Lecture 9 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 9 Comp 303 : Programming Techniques Page 1 Last lecture...
CSE 331 Software Design and Implementation. Lecture 14 Generics 2
CSE 331 Software Design and Implementation Lecture 14 Generics 2 Zach Tatlock / Spring 2018 Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping Using wildcards
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Kevin Zatloukal Summer 2017 Data Abstraction: Abstract Data Types (ADTs) (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock)
Software Engineering Design & Construction
Winter Semester 16/17 Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt Decorator Pattern Intent of the Decorator Pattern We need
Type Hierarchy. Lecture 6: OOP, autumn 2003
Type Hierarchy Lecture 6: OOP, autumn 2003 The idea Many types have common behavior => type families share common behavior organized into a hierarchy Most common on the top - supertypes Most specific at
Software Engineering Design & Construction
Winter Semester 17/18 Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt A Critical View on Inheritance 2 A Critical View On Inheritance
CSE341, Fall 2011, Lecture 26 Summary
CSE341, Fall 2011, Lecture 26 Summary Standard Disclaimer: This lecture summary is not necessarily a complete substitute for attending class, reading the associated code, etc. It is designed to be a useful
Programming Languages Seminar. Lecture in the subject of. Yair Moshe
Programming Languages Seminar Lecture in the subject of Yair Moshe Partly based on the book: Program Development in Java Abstraction, Specification and Object-Oriented Design / Barbara Liskov & John Guttag
Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt
Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt Winter Semester 16/17 Decorator Pattern Intent of the Decorator Pattern We need
CSE 331 Software Design and Implementation. Lecture 14 Generics 2
CSE 331 Software Design and Implementation Lecture 14 Generics 2 James Wilcox / Winter 2016 Hi, I m James! Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping
Lecture 4: Procedure Specifications
Lecture 4: Procedure Specifications 4.1. Introduction In this lecture, we ll look at the role played by specifications of methods. Specifications are the linchpin of team work. It s impossible to delegate
Equality. Michael Ernst. CSE 331 University of Washington
Equality Michael Ernst CSE 331 University of Washington Object equality A simple idea Two objects are equal if they have the same value A subtle idea intuition can be misleading Same object/reference,
Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107
A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105
CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17
List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code
Software Engineering Design & Construction
Winter Semester 16/17 Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt Liskov Substitution Principle 2 Liskov Substitution Principle
Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation Lecture 15 Generics 2 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now
CSE 331 Software Design and Implementation. Lecture 15 Generics 2
CSE 331 Software Design and Implementation Lecture 15 Generics 2 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now
Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)
Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3
1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides
1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of
Don t Believe the Hype. CS152: Programming Languages. Lecture 21 Object-Oriented Programming. Class-based OOP. So what is OOP?
Don t Believe the Hype CS152: Programming Languages Lecture 21 Object-Oriented Programming Dan Grossman Spring 2011 OOP lets you: 1. Build some extensible software concisely 2. Exploit an intuitive analogy
CSE wi Midterm Exam 2/8/18. Name UW ID #
Name UW ID # There are 11 questions worth a total of 120 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,
Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1
Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Kevin Zatloukal Fall 2017 Representation Invariants & Abstraction Functions (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock)
CSE 331 Final Exam 3/16/15 Sample Solution
Question 1. (12 points, 3 each) A short design exercise. Suppose Java did not include a Set class in the standard library and we need to store a set of Strings for an application. We know that the maximum
Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.
Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar
CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.
Name Solution The exam is closed book and closed electronics. One page of notes is allowed. The exam has 6 regular problems and 1 bonus problem. Only the regular problems will count toward your final exam
Chapter 5 Object-Oriented Programming
Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares
CS 215 Software Design Sample midterm solutions
Software Design Sample midterm solutions 1. The administration at Happy Valley School District is redesigning the software that manages information about its students. It has identified an abstract class
CS-202 Introduction to Object Oriented Programming
CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction
Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014
Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class
CSE wi Midterm Exam 2/8/18 Sample Solution
Remember: For all of the questions involving proofs, assertions, invariants, and so forth, you should assume that all numeric quantities are unbounded integers (i.e., overflow can not happen) and that
CS-XXX: Graduate Programming Languages. Lecture 22 Class-Based Object-Oriented Programming. Dan Grossman 2012
CS-XXX: Graduate Programming Languages Lecture 22 Class-Based Object-Oriented Programming Dan Grossman 2012 PL Issues for OOP? OOP lets you: 1. Build some extensible software concisely 2. Exploit an intuitive
Inheritance and object compatibility
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not the other way around Examples: reference/pointer can
Design Patterns. Introduction. Oliver Haase
Design Patterns Introduction Oliver Haase An instrument, a tool, an utensil, whatsoever it be, if it be fit for the purpose it was made for, it is as it should be though he perchance that made and fitted
6.170 Lecture 6 Procedure specifications MIT EECS
6.170 Lecture 6 Procedure specifications MIT EECS Outline Satisfying a specification; substitutability Stronger and weaker specifications Comparing by hand Comparing via logical formulas Comparing via
ITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract
Last Time: Object Design. Comp435 Object-Oriented Design. Last Time: Responsibilities. Last Time: Creator. Last Time: The 9 GRASP Patterns
Last Time: Object Design Comp435 Object-Oriented Design Week 7 Computer Science PSU HBG The main idea RDD: Responsibility-Driven Design Identify responsibilities Assign them to classes and objects Responsibilities
Super-Classes and sub-classes
Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an
Inheritance (Chapter 7)
Inheritance (Chapter 7) Prof. Dr. Wolfgang Pree Department of Computer Science University of Salzburg cs.uni-salzburg.at Inheritance the soup of the day?! Inheritance combines three aspects: inheritance
Practice for Chapter 11
Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing
CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.
Name The exam is closed book, closed notes, and closed electronics. Please wait to turn the page until everyone is told to begin. Score / 54 1. / 12 2. / 12 3. / 10 4. / 10 5. / 10 Bonus: 1. / 6 2. / 4
MIT EECS Michael Ernst Saman Amarasinghe
6.170 Lecture 11 Equality MIT EECS Michael Ernst Saman Amarasinghe 1 bject equality A simple idea we have intuitions about equality: Two objects are equal if they have the same value Two objects are equal
6.170 Lecture 7 Abstract Data Types MIT EECS
6.170 Lecture 7 Abstract Data Types MIT EECS Outline 1. What is an abstract data type (ADT)? 2. How to specify an ADT immutable mutable 3. The ADT methodology 2 What is an ADT? Procedural abstraction Abstracts
ITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract
Comparing procedure specifications
Comparing procedure specifications CSE 331 University of Washington Michael Ernst Outline Satisfying a specification; substitutability Stronger and weaker specifications Comparing by hand Comparing via
Principles of Object-Oriented Design
Principles of Object-Oriented Design 1 The Object-Oriented... Hype What are object-oriented (OO) methods? OO methods provide a set of techniques for analysing, decomposing, and modularising software system
CS 520 Theory and Practice of Software Engineering Fall 2018
Today CS 520 Theory and Practice of Software Engineering Fall 2018 Object Oriented (OO) Design Principles September 13, 2018 Code review and (re)design of an MVC application (and encapsulation) Polymorphism
Software Engineering Design & Construction
Winter Semester 17/18 A smart home has many features that are controlled automatically: Heating, Lighting, Shutters, Software Engineering Design & Construction We want to develop a software that helps
Self-review Questions
7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Hal Perkins Spring 2017 Exceptions and Assertions 1 Outline General concepts about dealing with errors and failures Assertions: what, why, how For things you believe
Lecture 16: Case Study: The Java Collections API
Lecture 16: Case Study: The Java Collections API You can t be a competent Java programmer without understanding the crucial parts of the Java library. The basic types are all in java.lang, and are part
CSE331 Winter 2014, Final Examination March 17, 2014 Please do not turn the page until 8:30. Rules:
CSE331 Winter 2014, Final Examination March 17, 2014 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 10:20. There are 116 points total,
Specifications. CSE 331 Spring 2010
Specifications CSE 331 Spring 2010 The challenge of scaling software Small programs are simple and malleable easy to write easy to change Big programs are (often) complex and inflexible hard to write hard
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Kevin Zatloukal Fall 2017 Module Design & Style (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) The limits of scaling Can
Classes, interfaces, & documentation. Review of basic building blocks
Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform
CS 520 Theory and Practice of Software Engineering Fall 2017
CS 520 Theory and Practice of Software Engineering Fall 2017 OO design principles September 14, 2017 Today Code review and (re)design of an MVC application OO design principles Information hiding (and
Object Oriented Programming. Java-Lecture 11 Polymorphism
Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class
Intro to: Design Principles
Intro to: Design Principles Pragmatic Programmer: Eliminate Effects Between Unrelated Things design components that are: self-contained, independent, and have a single, well-defined purpose Software Design
Programming II (CS300)
1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes
Last class. -More on polymorphism -super -Introduction to interfaces
Last class -More on polymorphism -super -Introduction to interfaces Interfaces Sometimes in Java, we will have 2 classes that both share a similar structure, but neither of them is clearly the parent or
Object-Oriented Concepts and Design Principles
Object-Oriented Concepts and Design Principles Signature Specifying an object operation or method involves declaring its name, the objects it takes as parameters and its return value. Known as an operation
Data Abstraction. Hwansoo Han
Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed
Solutions to Quiz 1 (March 14, 2016)
MIT 6.005: Software Construction Max Goldman revised Wednesday 16 th March, 2016, 14:08 Solutions to Quiz 1 (March 14, 2016) Problem 1 (Multiple Choice) (20 points). (a) Which of the following must be
Introduction to Object-Oriented Programming
Polymorphism 1 / 19 Introduction to Object-Oriented Programming Today we ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll.
Week 7. Statically-typed OO languages: C++ Closer look at subtyping
C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula
Object typing and subtypes
CS 242 2012 Object typing and subtypes Reading Chapter 10, section 10.2.3 Chapter 11, sections 11.3.2 and 11.7 Chapter 12, section 12.4 Chapter 13, section 13.3 Subtyping and Inheritance Interface The
Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance
Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass
The Liskov Substitution Principle
Agile Design Principles: The Liskov Substitution Principle Based on Chapter 10 of Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices, Prentice Hall, 2003 and on Barbara Liskov
Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism
Lecture Outline Parametric Polymorphism and Java Generics Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards
Inheritance and Polymorphism
Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg
Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L
Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive
Design Patterns: State, Bridge, Visitor
Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement
Introduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
CSE331 Winter 2014, Midterm Examination February 12, 2014
CSE331 Winter 2014, Midterm Examination February 12, 2014 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 11:20. There are 100 points
Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright
Polymorphism Object Orientated Programming in Java Benjamin Kenwright Quizzes/Labs Every single person should have done Quiz 00 Introduction Quiz 01 - Java Basics Every single person should have at least
Rules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
OOP Design Conclusions and Variations
CS108, Stanford Handout #20 Fall, 2008-09 Osvaldo Jiménez OOP Design Conclusions and Variations Thanks to Nick Parlante for much of this handout Part 1 -- Mainstream OOP Design First, we have the standard,
Inheritance, cont. Notes Chapter 6 and AJ Chapters 7 and 8
Inheritance, cont. Notes Chapter 6 and AJ Chapters 7 and 8 1 Preconditions and Inheritance precondition what the method assumes to be true about the arguments passed to it inheritance (is-a) a subclass
An Introduction to Subtyping
An Introduction to Subtyping Type systems are to me the most interesting aspect of modern programming languages. Subtyping is an important notion that is helpful for describing and reasoning about type
Java Primer. CITS2200 Data Structures and Algorithms. Topic 2
CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,
CS 320 Introduction to Software Engineering Spring March 06, 2017
CS 320 Introduction to Software Engineering Spring 2017 March 06, 2017 Recap: types of Polymorphism Recap: types of Polymorphism Ad-hoc polymorphism (e.g., operator overloading) a + b String vs. int, double,
Universe Type System for Eiffel. Annetta Schaad
Universe Type System for Eiffel Annetta Schaad Semester Project Report Software Component Technology Group Department of Computer Science ETH Zurich http://sct.inf.ethz.ch/ SS 2006 Supervised by: Dipl.-Ing.