Software Construction

Similar documents
2IP15 Programming Methods

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

The following topics will be covered in this course (not necessarily in this order).

Introduction to Programming Using Java (98-388)

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Objects and Iterators

Software Construction

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Top Down Design vs. Modularization

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

CSE 331 Spring 2018 Midterm

Software Construction

Inheritance and Interfaces

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Week 16: More on Collections and Immutability

Declarations and Access Control SCJP tips

MIT EECS Michael Ernst Saman Amarasinghe

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

COURSE 2 DESIGN PATTERNS

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Expected properties of equality

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

2IP15 Programming Methods

CSE 331 Software Design & Implementation

Java Review: Objects

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Abstract Classes and Interfaces

Inheritance. Transitivity

CSE 331 Software Design & Implementation

Chapter 5 Object-Oriented Programming

JAVA MOCK TEST JAVA MOCK TEST II

CMSC 132: Object-Oriented Programming II

Software Construction

Introduction to Object-Oriented Programming

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Implementing Object Equivalence in Java Using the Template Method Design Pattern

Equality. Michael Ernst. CSE 331 University of Washington

[ L5P1] Object-Oriented Programming: Advanced Concepts

Equality. Michael Ernst. CSE 331 University of Washington

CMSC 132: Object-Oriented Programming II

Subclassing for ADTs Implementation

EINDHOVEN UNIVERSITY OF TECHNOLOGY

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Another IS-A Relationship

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Java Object Oriented Design. CSC207 Fall 2014

Concepts of Programming Languages

The class Object. Lecture CS1122 Summer 2008

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Polymorphism. return a.doublevalue() + b.doublevalue();

Programming II (CS300)

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Programming II (CS300)

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

15CS45 : OBJECT ORIENTED CONCEPTS

Chapter 14 Abstract Classes and Interfaces

Self-review Questions

Type Hierarchy. Lecture 6: OOP, autumn 2003

VIRTUAL FUNCTIONS Chapter 10

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

CS558 Programming Languages Winter 2013 Lecture 8

Implications of Substitution עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

This page intentionally left blank

Introduction to Object-Oriented Programming

Chapter 13 Abstract Classes and Interfaces

Chapter 10 Classes Continued. Fundamentals of Java

INSTRUCTIONS TO CANDIDATES

More Relationships Between Classes

Exam 2. Topics. Preconditions vs. Exceptions. Exam 2 Review. Exam 2 on Thursday, March 29 th. Closed book, closed computer, closed phone

Java Fundamentals (II)

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS260 Intro to Java & Android 03.Java Language Basics

Announcements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington

CIS 120 Final Exam 15 December 2017

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

C++ Programming: Polymorphism

Subtype Polymorphism

Name Section Number. CS210 Exam #4 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

A final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.

CS 3 Introduction to Software Engineering. 5: Iterators

Software Construction

First IS-A Relationship: Inheritance

CPS 506 Comparative Programming Languages. Programming Language

Inheritance and object compatibility

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Collections and Iterators. Collections

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

Lecture 2: Java & Javadoc

Conformance. Object-Oriented Programming Spring 2015

Example: Count of Points

Transcription:

Lecture 7: Type Hierarchy, Iteration Abstraction Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology Group www.win.tue.nl/ wstomv/edu/sc-hse c 2014, T. Verhoeff @ TUE.NL 1/37 Software Construction: Lecture 7

Overview Feedback on homework Series 6 Further details on Java classes Type Hierarchy: Subtyping Iteration Abstraction: Ch. 10.1.5 in Eck; Ch. 3 in Burris Strategy Pattern: Ch. 7 in Burris c 2014, T. Verhoeff @ TUE.NL 2/37 Software Construction: Lecture 7

Homework Series 6 In general: Rejected work must be improved; see FAQ DiceGame Robust, Statistics: robustness + tests DiceGame OO + Alternative: several interdependent classes Mutable vs Immutable Fractions: see further down c 2014, T. Verhoeff @ TUE.NL 3/37 Software Construction: Lecture 7

Data Abstraction in Java: References, Sharing, Aliasing A variable of a primitive type has as value a value of that type. A variable of class type T does not have an object of type T as value, but either the name of an object of type T, or the special value null. This name is a unique identifier of that object (a.k.a. reference). This allows sharing, a.k.a. aliasing: two distinct variables name the same object. It can help improve (memory and time) efficiency by avoiding the copying of data. But it complicates reasoning. Operator == on expressions of a class type compares object names, and not the object states: "abc"!= "abc" c 2014, T. Verhoeff @ TUE.NL 4/37 Software Construction: Lecture 7

Data Abstraction in Java: Aliasing Example Card u = new Card(Rank.Ace, Suit.Spades); Card v = new Card(Rank.Ace, Suit.Spades); Card w = new Card(Rank.Queen, Suit.Hearts); Card y = u; // u, v, and w name (refer to) distinct objects: // u!= v && v!= w && w!= u // u and v refer to objects having the same value (state) // u and w refer to objects having different values // u and y name the same object (aliasing): u == y c 2014, T. Verhoeff @ TUE.NL 5/37 Software Construction: Lecture 7

Changeability of variables versus objects Note the difference between (changing) the state of a variable (i.e., its primitive value or the name of an object it referes to) and the state of an object. These can change independently: A variable can be made to refer to another object (unless it is final), without changing the state of the objects involved. The state of an object can be changed (unless its class is immutable), without changing the variables that refer to it. c 2014, T. Verhoeff @ TUE.NL 6/37 Software Construction: Lecture 7

Data Abstraction: Mutability A data type T implemented as a class is said to be immutable when none of its methods modifies this or a parameter of type T ; i.e., the state of a T object cannot change after construction. N.B. A T method could still modify a parameter of another type. So, not all side effects are eliminated. E.g.: String; immutable/fraction Immutable types need various/parameterized constructors. It is said to be mutable otherwise. E.g.: arrays; mutable/fraction c 2014, T. Verhoeff @ TUE.NL 7/37 Software Construction: Lecture 7

Data Abstraction: equality and similarity Two objects are at the time of comparison said to be equal when they are behaviorally indistinguishable: every sequence of operations (queries and commands), when applied to both objects, yields the same result. a.equals(b); e.g. "abc".equals("abc") true int[] a = new int[] { 1, 2 }, b = new int[] { 1, 2 }; a.equals(b) false similar when they are observationally indistinguishable: every sequence of queries only (no commands), when applied to both objects, yields the same result. a.similar(b) (not predefined!): a.similar(b) true c 2014, T. Verhoeff @ TUE.NL 8/37 Software Construction: Lecture 7

Data Abstraction: Comparison of (im)mutable objects In general: a == b implies a.equals(b), but not vice versa. Mutable objects are equal when they are the same object (==): Otherwise, you can change one without changing the other. a.equals(b) inherited from Object (returning a == b) suffices In general: a.equals(b) implies a.similar(b), but not vice versa. Immutable objects are equal when they are similar (same state): Immutable types must override implementation of equals() to coincide with similar(). c 2014, T. Verhoeff @ TUE.NL 9/37 Software Construction: Lecture 7

Data Abstraction: equals() equals() must be reflexive: a.equals(a) symmetric: a.equals(b) == b.equals(a) transitive: if a.equals(b) && b.equals(c) then a.equals(c) A class can have several (overloaded) equals() methods. c 2014, T. Verhoeff @ TUE.NL 10/37 Software Construction: Lecture 7

Data Abstraction: clone() To offer method clone(), a class must implement Cloneable; otherwise, clone() will throw CloneNotSupportedException. clone() returns a copy of this. The copy should be similar but not identical to this. The default implementation inherited from Object constructs a new object and copies all instance variables ( shallow copy ). This is sufficient for immutable objects. Mutable objects should implement their own clone() (doing a deep copy ) However, it is better to avoid clone. c 2014, T. Verhoeff @ TUE.NL 11/37 Software Construction: Lecture 7

Alternatives to clone() http://en.wikipedia.org/wiki/clone_(java_method) http://www.javapractices.com/topic/topicaction.do?id=71 http://www.xenoveritas.org/blog/xeno/java_copy_constructors_and_clone http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Copy constructor, e.g. for mutable fractions: 1 /** 2 * Constructs (a copy of) a fraction for given fraction. 3 * 4 * @param fraction given fraction to copy 5 * @post new fraction with value {@code fraction} constructed 6 */ 7 public Fraction(final Fraction fraction) { 8 this(fraction.getnumerator(), fraction.getdenominator()); 9 } c 2014, T. Verhoeff @ TUE.NL 12/37 Software Construction: Lecture 7

Mutable versus Immutable Immutable Mutable Efficiency + Reasoning ++ equals() ++ clone() ++ Concerns: Sharing, (partial) copying of data Immutable classes never need to clone(). c 2014, T. Verhoeff @ TUE.NL 13/37 Software Construction: Lecture 7

Inheritance A new class can be defined by extending an existing class: public class RuntimeException extends Exception public class IllegalRequestException extends RuntimeException public class StatisticsWithVariance extends Statistics Terminology: StatisticsWithVariance is a subclass of Statistics; Statistics is the superclass of StatisticsWithVariance Subclass inherits all instance variables and methods in superclass, both method signatures and method implementations (if present). It is strongly recommended to inherit also the method contracts. The compiler does not enforce inheritance of method contracts. A subclass can extend only one class; it can add new methods and instance variables, and override inherited methods. c 2014, T. Verhoeff @ TUE.NL 14/37 Software Construction: Lecture 7

Liskov Substitution Principle (LSP) Let U be a subclass (possibly in multiple steps) of T. Type U is called a subtype of type T, when In each place where an object of type T can be used, you can substitute an object of type U, without affecting the correctness of the program. It is good practice to ensure that subclasses are also subtypes. A subtype is not only syntactically a substitute (it compiles), but also semantically (it works). This means that also all method contracts are inherited. c 2014, T. Verhoeff @ TUE.NL 15/37 Software Construction: Lecture 7

1 public class Fraction { Liskov Substitution Principle Violated 2 /** (Command) Adds q to this. */ 3 public void add(fraction q) { "adds q to this" } 4 } 5 6 class MyFraction extends Fraction { 7 @Override 8 public void add(fraction q) { "multiplies q to this" } 9 } 10... 11 Fraction v; 12 v = condition? new Fraction() : new MyFraction(); 13 v.add(v); 14 /* assert: v was doubled */ c 2014, T. Verhoeff @ TUE.NL 16/37 Software Construction: Lecture 7

Abstract Classes (no details, just the concept) A method can be declared abstract. An abstract method does not have a complete implementation. A class containing abstract methods must be declared abstract. An abstract class cannot be instantiated. A subclass can provide an implementation for an abstract method inherited from the superclass, by overriding the method. It is recommended to annotate such methods: @Override public String stringof() {... } c 2014, T. Verhoeff @ TUE.NL 17/37 Software Construction: Lecture 7

Interfaces (no details, just the concept) An interface defines a collection of method signatures, with contracts An interface has neither instance variables, nor method implementations. It can define constants with public static final... An interface is somewhat like a class with only abstract methods. A class can implement one or more interfaces, by implementing each of the methods in the interface(s). An interface can be viewed as a type : Its values are the values of all classes that implement the interface. c 2014, T. Verhoeff @ TUE.NL 18/37 Software Construction: Lecture 7

Generic Classes and Interfaces (no details, just the concept) A type can be defined to have one or more type parameters. Example: List<E>, ArrayList<E> The generic type parameter must be replaced by a specific type. Example: ArrayList<String>, List<List<Long>> c 2014, T. Verhoeff @ TUE.NL 19/37 Software Construction: Lecture 7

UML Class Diagrams SuperClass AbstractClass «interface» Interface T GenericClass Subclass Subclass Subclass c 2014, T. Verhoeff @ TUE.NL 20/37 Software Construction: Lecture 7

Iteration Iterate over a collection : visit each item exactly once (possibly in a prescribed order) Ad hoc approach uses standard for-loop: String[] a; // collection represented by an array for (int i = 0; i!= a.length; ++ i) {... a[i]... } ArrayList<String> L; // collection represented by an ArrayList for (int i = 0; i!= L.size(); ++ i) {... L.get(i)... } How to iterate over a Set? c 2014, T. Verhoeff @ TUE.NL 21/37 Software Construction: Lecture 7

Iteration Abstraction Iteration Abstraction : Facility for iteration that abstracts from type of collection type of its items implementation details of how to accomplish iteration e.g. choosing an order Iteration abstraction provides a uniform solution. Unfortunatly, details of iteration abstraction are programming-language specific. c 2014, T. Verhoeff @ TUE.NL 22/37 Software Construction: Lecture 7

Enhanced for Statement, or the for-each Loop New in Java 5.0: for ( Type Identifier : Expression ) Statement Identifier is a local variable, whose values are of the declared Type, iterating over the collection defined by Expression. Read as for each... in.... Expression can be an array, e.g. obtained through method values() from an enum a type that implements interface Iterable (a subtype of Iterable) c 2014, T. Verhoeff @ TUE.NL 23/37 Software Construction: Lecture 7

for-each Loop Examples Iterate over an array: float[] a; for (float f : a) {... f... } Iterate over the values in an enum: private enum PrimColor { RED, GREEN, BLUE } for (PrimColor c : PrimColor.values()) {... c... } Iterate over a type that implements Iterable HashSet<Card> cards; for (Card card : cards) {... card... } c 2014, T. Verhoeff @ TUE.NL 24/37 Software Construction: Lecture 7

Semantics of enhanced for Statement: for ( T v : E ) S if E is an array: T[] r = E; // fresh identifier r; E evaluated only once // r is a reference, and not a copy for (int i = 0; i!= r.length; ++ i) { T v = r[i]; S // operates on v (N.B. i is invisible) } if E is subtype of Iterable<T> (i.e., E provides a default iterator): for (Iterator<T> iter = E.iterator(); iter.hasnext(); ) { T v = iter.next(); S // operates on v } c 2014, T. Verhoeff @ TUE.NL 25/37 Software Construction: Lecture 7

Interfaces Iterable and Iterator public interface Iterable<T> { /** Returns an iterator for a collection over type T. */ Iterator<T> iterator(); } public interface Iterator<T> { /** Returns whether a next item is available. */ boolean hasnext(); /** Returns the next item in the iteration. * @throws NoSuchElementException if not available */ T next(); } void remove(); // optional (not treated here; see book) N.B. Cannot invoke remove() in for-each loop (anonymous iterator). c 2014, T. Verhoeff @ TUE.NL 26/37 Software Construction: Lecture 7

Iterator Design Pattern Class Diagram Client Iterable T Iterator T iterator(): Iterator<T> hasnext(): boolean next(): T remove() MyCollection MyCollectionIterator c 2014, T. Verhoeff @ TUE.NL 27/37 Software Construction: Lecture 7

Iterator and iterator method that creates an iterator 1 import java.util.iterator; 2 3 /** C is collection over type T (comparable to ArrayList<T>) */ 4 public class C implements Iterable<T> { 5 private... r; // data representation of the collection 6 7 public Iterator<T> iterator() { return new ForIterator(...); } 8 9 private class ForIterator implements Iterator<T> { 10 private... s; // private state of iterator 11 12 ForIterator(...) {... s... } // constructs initial state 13 14 public boolean hasnext() {... r, s... } 15 16 public T next() throws NoSuchElementException {... r, s... } 17 } 18 } c 2014, T. Verhoeff @ TUE.NL 28/37 Software Construction: Lecture 7

Iterators in general Standard iterator to be used in for-each loop: Collection class must implement interface Iterable<T> and define method iterator() returning an Iterator<T>. See example Range.java Iterator in general (not usable in for-each loop): Collection class must define one or more methods returning an Iterator<T>. The name of the iterator constructor is not prescribed. See example DownRange.java c 2014, T. Verhoeff @ TUE.NL 29/37 Software Construction: Lecture 7

Iterators: Loose Ends Iterators cannot be reused. Each iteration involves a new iterator object. Multiple iterators over the same collection can be active at the same time E.g. iterations over the same collection can be nested. This involves multiple iterator objects. c 2014, T. Verhoeff @ TUE.NL 30/37 Software Construction: Lecture 7

Design Issues Data types that store a collection of items typically offer one or more iterators. Mutable collections require that the loop using an iterator does not change the collection outside the iterator. Doing so will result in a ConcurrentModificationException. The Iterator interface offers one safe modification operation: remove(), but it is not always implemented. For use in the for-each statement, the collection should implement Iterable<...> and provide the iterator constructor iterator(). Other iterators must be used through standard loops using hasnext() and next(). c 2014, T. Verhoeff @ TUE.NL 31/37 Software Construction: Lecture 7

Strategy Design Pattern (Burris, Chapter 7) Problem: Accommodate multiple implementations of same class Problem: Possibility to select implementation at runtime Solution: Put specification of class in (abstract) class or interface. Put implementations in subclasses of specification. Declare variable with specification type. Assign to variable a class of an implementation type. c 2014, T. Verhoeff @ TUE.NL 32/37 Software Construction: Lecture 7

Strategy Design Pattern: Example (See JUnit4Examples) 1 public abstract class AbstractPowerClass { 2 /**... Specification... */ 3 public abstract long power(int a, int b) throws...; 4 } 5 6 public class PowerByRepeatedMultiplication extends AbstractPowerClass { 7 @Override 8 public boolean long power(int a, int b) { 9 /*... implementation by repeated multiplication */ 10 } 11 } 12 13 public class PowerByRepeatedSquaring extends AbstractPowerClass { 14 @Override 15 public boolean long power(int a, int b) { 16 /*... implementation by repeated squaring/multiplication */ 17 } 18 } c 2014, T. Verhoeff @ TUE.NL 33/37 Software Construction: Lecture 7

Strategy Design Pattern: Example (continued) 1 public class Context { 2 3 // Declare variable using the specification class 4 private AbstractPowerClass mypower; 5 6 public Context(boolean slow) { 7 // choose concrete implementation 8 if (slow) { 9 mypower = new PowerByRepeatedMultiplication(); 10 } else { 11 mypower = new PowerByRepeatedSquaring(); 12 } 13 14 // use the chosen implementation 15... mypower.power(...,...)... 16 } 17 } c 2014, T. Verhoeff @ TUE.NL 34/37 Software Construction: Lecture 7

Strategy Pattern Class Diagram Context AbstractPowerClass power(int, int) : long PowerByRepeatedMultiplication power(int, int) : long PowerByRepeatedSquaring power(int, int) : long c 2014, T. Verhoeff @ TUE.NL 35/37 Software Construction: Lecture 7

Homework Series 7 Read in Eck: 5.3, 5.5, 10.1.(4, 5), 10.2.1; browse 5.7 Read in Burris: Chapter 3 (Iterator), Chapter 7 (Strategy) Exercises 3, 4, 5 of Test Driven Development Iteratble IntRelation will be peer reviewed c 2014, T. Verhoeff @ TUE.NL 36/37 Software Construction: Lecture 7

Summary Aliasing, (im)mutable, similar, equals, clone Inheritance, subtyping, extends, implements An iterator object provides iteration abstraction: visit each element of a collection exactly once, without worrying about the underlying traversal mechanism. An Iterator<T> object provides methods hasnext() and next(). The for-each loop uses iterator() from Iterable<T>. c 2014, T. Verhoeff @ TUE.NL 37/37 Software Construction: Lecture 7