Software Construction
|
|
- Madeline Park
- 5 years ago
- Views:
Transcription
1 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 wstomv/edu/sc-hse c 2014, T. TUE.NL 1/37 Software Construction: Lecture 7
2 Overview Feedback on homework Series 6 Further details on Java classes Type Hierarchy: Subtyping Iteration Abstraction: Ch in Eck; Ch. 3 in Burris Strategy Pattern: Ch. 7 in Burris c 2014, T. TUE.NL 2/37 Software Construction: Lecture 7
3 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. TUE.NL 3/37 Software Construction: Lecture 7
4 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. TUE.NL 4/37 Software Construction: Lecture 7
5 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. TUE.NL 5/37 Software Construction: Lecture 7
6 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. TUE.NL 6/37 Software Construction: Lecture 7
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. TUE.NL 7/37 Software Construction: Lecture 7
8 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. TUE.NL 8/37 Software Construction: Lecture 7
9 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. TUE.NL 9/37 Software Construction: Lecture 7
10 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. TUE.NL 10/37 Software Construction: Lecture 7
11 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. TUE.NL 11/37 Software Construction: Lecture 7
12 Alternatives to clone() Copy constructor, e.g. for mutable fractions: 1 /** 2 * Constructs (a copy of) a fraction for given fraction. 3 * 4 fraction given fraction to copy 5 new fraction with value {@code fraction} constructed 6 */ 7 public Fraction(final Fraction fraction) { 8 this(fraction.getnumerator(), fraction.getdenominator()); 9 } c 2014, T. TUE.NL 12/37 Software Construction: Lecture 7
13 Mutable versus Immutable Immutable Mutable Efficiency + Reasoning ++ equals() ++ clone() ++ Concerns: Sharing, (partial) copying of data Immutable classes never need to clone(). c 2014, T. TUE.NL 13/37 Software Construction: Lecture 7
14 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. TUE.NL 14/37 Software Construction: Lecture 7
15 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. TUE.NL 15/37 Software Construction: Lecture 7
16 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 { 8 public void add(fraction q) { "multiplies q to this" } 9 } Fraction v; 12 v = condition? new Fraction() : new MyFraction(); 13 v.add(v); 14 /* assert: v was doubled */ c 2014, T. TUE.NL 16/37 Software Construction: Lecture 7
17 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 public String stringof() {... } c 2014, T. TUE.NL 17/37 Software Construction: Lecture 7
18 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. TUE.NL 18/37 Software Construction: Lecture 7
19 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. TUE.NL 19/37 Software Construction: Lecture 7
20 UML Class Diagrams SuperClass AbstractClass «interface» Interface T GenericClass Subclass Subclass Subclass c 2014, T. TUE.NL 20/37 Software Construction: Lecture 7
21 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. TUE.NL 21/37 Software Construction: Lecture 7
22 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. TUE.NL 22/37 Software Construction: Lecture 7
23 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. TUE.NL 23/37 Software Construction: Lecture 7
24 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. TUE.NL 24/37 Software Construction: Lecture 7
25 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. TUE.NL 25/37 Software Construction: Lecture 7
26 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. 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. TUE.NL 26/37 Software Construction: Lecture 7
27 Iterator Design Pattern Class Diagram Client Iterable T Iterator T iterator(): Iterator<T> hasnext(): boolean next(): T remove() MyCollection MyCollectionIterator c 2014, T. TUE.NL 27/37 Software Construction: Lecture 7
28 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 ForIterator(...) {... s... } // constructs initial state public boolean hasnext() {... r, s... } public T next() throws NoSuchElementException {... r, s... } 17 } 18 } c 2014, T. TUE.NL 28/37 Software Construction: Lecture 7
29 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. TUE.NL 29/37 Software Construction: Lecture 7
30 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. TUE.NL 30/37 Software Construction: Lecture 7
31 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. TUE.NL 31/37 Software Construction: Lecture 7
32 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. TUE.NL 32/37 Software Construction: Lecture 7
33 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 { 8 public boolean long power(int a, int b) { 9 /*... implementation by repeated multiplication */ 10 } 11 } public class PowerByRepeatedSquaring extends AbstractPowerClass { 15 public boolean long power(int a, int b) { 16 /*... implementation by repeated squaring/multiplication */ 17 } 18 } c 2014, T. TUE.NL 33/37 Software Construction: Lecture 7
34 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 } // use the chosen implementation mypower.power(...,...) } 17 } c 2014, T. TUE.NL 34/37 Software Construction: Lecture 7
35 Strategy Pattern Class Diagram Context AbstractPowerClass power(int, int) : long PowerByRepeatedMultiplication power(int, int) : long PowerByRepeatedSquaring power(int, int) : long c 2014, T. TUE.NL 35/37 Software Construction: Lecture 7
36 Homework Series 7 Read in Eck: 5.3, 5.5, 10.1.(4, 5), ; 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. TUE.NL 36/37 Software Construction: Lecture 7
37 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. TUE.NL 37/37 Software Construction: Lecture 7
2IP15 Programming Methods
Lecture 5: Iteration Abstraction 2IP15 Programming Methods From Small to Large Programs Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering
More informationData abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003
Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation
More informationThe following topics will be covered in this course (not necessarily in this order).
The following topics will be covered in this course (not necessarily in this order). Introduction The course focuses on systematic design of larger object-oriented programs. We will introduce the appropriate
More informationIntroduction 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;
More informationContents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix
PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring
More informationCanonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering
CSC40232: SOFTWARE ENGINEERING Professor: Jane Cleland Huang Canonical Form sarec.nd.edu/courses/se2017 Department of Computer Science and Engineering Canonical Form Canonical form is a practice that conforms
More informationObjects and Iterators
Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a
More informationSoftware Construction
Lecture 5: Robustness, Exceptions Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationTop 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
More informationWhat is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one
Iterators 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 9-2 2-2 What is an Iterator? An iterator is an abstract data
More informationCSE 331 Spring 2018 Midterm
CSE 331 Spring 2018 Midterm Name There are 8 questions worth a total of 93 points. Please budget your time so that you get as many points as possible. We have done our best to make a test that folks can
More informationSoftware Construction
Lecture 1: Introduction Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology Group
More informationInheritance and Interfaces
Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical
More informationInheritance. 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
More informationWeek 16: More on Collections and Immutability
Week 16: More on Collections and Immutability Jack Hargreaves jxh576@cs.bham.ac.uk Febuary 9, 2012 1 Collections API Last week we looked at Collection, List, Set and Map the basic data type interfaces
More informationDeclarations and Access Control SCJP tips
Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for
More informationMIT 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
More informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationCOURSE 2 DESIGN PATTERNS
COURSE 2 DESIGN PATTERNS CONTENT Fundamental principles of OOP Encapsulation Inheritance Abstractisation Polymorphism [Exception Handling] Fundamental Patterns Inheritance Delegation Interface Abstract
More informationContents. 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
More informationExpected 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??
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More information2IP15 Programming Methods
Lecture 3: Robustness 2IP15 Programming Methods From Small to Large Programs Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology
More informationCSE 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
More informationJava Review: Objects
Outline Java review Abstract Data Types (ADTs) Interfaces Class Hierarchy, Abstract Classes, Inheritance Invariants Lists ArrayList LinkedList runtime analysis Iterators Java references 1 Exam Preparation
More informationType 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...
More informationAbstract Classes and Interfaces
Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass
More informationInheritance. Transitivity
Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated
More informationCSE 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
More informationChapter 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
More informationJAVA MOCK TEST JAVA MOCK TEST II
http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationSoftware Construction
Lecture 11: Command Design Pattern Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology
More informationIntroduction to Object-Oriented Programming
Introduction to Object-Oriented Programming Object-Oriented Programming, Part 2 of 3 Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Object-Oriented Programming, Part 2 of 3 1 / 16
More informationInheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.
Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods
More informationImplementing Object Equivalence in Java Using the Template Method Design Pattern
Implementing Object Equivalence in Java Using the Template Method Design Pattern Daniel E. Stevenson and Andrew T. Phillips Computer Science Department University of Wisconsin-Eau Claire Eau Claire, WI
More informationEquality. Michael Ernst. CSE 331 University of Washington
Equality Michael Ernst CSE 331 University of Washington Object equality A simpleidea: Two objects are equal if they have the same value A subtle idea intuition can be misleading: Same object/reference,
More information[ L5P1] Object-Oriented Programming: Advanced Concepts
[ L5P1] Object-Oriented Programming: Advanced Concepts Polymorphism Polymorphism is an important and useful concept in the object-oriented paradigm. Take the example of writing a payroll application for
More informationEquality. 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,
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationSubclassing for ADTs Implementation
Object-Oriented Design Lecture 8 CS 3500 Fall 2009 (Pucella) Tuesday, Oct 6, 2009 Subclassing for ADTs Implementation An interesting use of subclassing is to implement some forms of ADTs more cleanly,
More informationEINDHOVEN UNIVERSITY OF TECHNOLOGY
EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics & Computer Science Exam Programming Methods, 2IP15, Wednesday 17 April 2013, 09:00 12:00 TU/e THIS IS THE EXAMINER S COPY WITH (POSSIBLY INCOMPLETE)
More informationMethod Overriding. Note that you can invoke the overridden method through the use of the keyword super.
Method Overriding The subclass is allowed to change the behavior inherited from its superclass, if needed. If one defines an instance method with its method name, parameters, and its return type, all identical
More informationAnother IS-A Relationship
Another IS-A Relationship Not all classes share a vertical relationship. Instead, some are supposed to perform the specific methods without a vertical relationship. Consider the class Bird inherited from
More informationAgenda. Objects and classes Encapsulation and information hiding Documentation Packages
Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics
More informationJava 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
More informationConcepts of Programming Languages
Concepts of Programming Languages Lecture 10 - Object-Oriented Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages
More informationThe class Object. Lecture CS1122 Summer 2008
The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationUNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED
UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance
More informationPolymorphism. return a.doublevalue() + b.doublevalue();
Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces
More informationProgramming 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
More informationAdvanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II
Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract
More informationSubclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented
Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and
More informationCore Java - SCJP. Q2Technologies, Rajajinagar. Course content
Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code
More informationCS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08
CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 17: Types and Type-Checking 25 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 What Are Types? Types describe the values possibly
More informationIndex. 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
More informationCONTENTS. 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
More information15CS45 : OBJECT ORIENTED CONCEPTS
15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?
More informationChapter 14 Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden
More informationSelf-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
More informationType 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
More informationVIRTUAL FUNCTIONS Chapter 10
1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions
More informationThe Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000
The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes
More informationCS558 Programming Languages Winter 2013 Lecture 8
OBJECT-ORIENTED PROGRAMMING CS558 Programming Languages Winter 2013 Lecture 8 Object-oriented programs are structured in terms of objects: collections of variables ( fields ) and functions ( methods ).
More informationImplications of Substitution עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון
Implications of Substitution עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap In this chapter we will investigate some of the implications of the principle of substitution in statically typed
More informationThis page intentionally left blank
This page intentionally left blank Absolute Java, Global Edition Table of Contents Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents Chapter 1 Getting Started 1.1 INTRODUCTION
More informationIntroduction 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.
More informationChapter 13 Abstract Classes and Interfaces
Chapter 13 Abstract Classes and Interfaces 1 Abstract Classes Abstraction is to extract common behaviors/properties into a higher level in the class hierarch so that they are shared (implemented) by subclasses
More informationChapter 10 Classes Continued. Fundamentals of Java
Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an
More informationINSTRUCTIONS TO CANDIDATES
NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING MIDTERM ASSESSMENT FOR Semester 2 AY2017/2018 CS2030 Programming Methodology II March 2018 Time Allowed 90 Minutes INSTRUCTIONS TO CANDIDATES 1. This
More informationMore Relationships Between Classes
More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to
More informationExam 2. Topics. Preconditions vs. Exceptions. Exam 2 Review. Exam 2 on Thursday, March 29 th. Closed book, closed computer, closed phone
Exam 2 Exam 2 on Thursday, March 29 th Exam 2 Review Closed book, closed computer, closed phone You are allowed two cheat pages Either a standard 8.5x11-sized sheet filled on both sides or two standard
More informationJava Fundamentals (II)
Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class
More informationIntroduction 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:
More informationZhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson
Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program
More informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationAnnouncements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018
CSE 331 Software Design and Implementation Lecture 10 Equality and Hashcode Announcements Leah Perlmutter / Summer 2018 Announcements This coming week is the craziest part of the quarter! Quiz 4 due tomorrow
More informationMotivations. Objectives. object cannot be created from abstract class. abstract method in abstract class
Motivations Chapter 13 Abstract Classes and Interfaces You have learned how to write simple programs to create and display GUI components. Can you write the code to respond to user actions, such as clicking
More informationCS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces
CS 112 Programming 2 Lecture 10 Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces 2 1 Motivations We have learned how to write simple programs to create and display GUI components.
More informationCSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington
CSE 3302 Lecture 3: Objects 2 September 2010 Nate Nystrom University of Texas at Arlington Administration Out of town this afternoon thru Monday HW1 due next Thursday 9/9 Types Last time: strongly typed
More informationCIS 120 Final Exam 15 December 2017
CIS 120 Final Exam 15 December 2017 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing
More informationCSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community
CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring
More informationC++ Programming: Polymorphism
C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function
More informationSubtype Polymorphism
Subtype Polymorphism For convenience, let U be a subtype of T. Liskov Substitution Principle states that T-type objects may be replaced with U-type objects without altering any of the desirable properties
More informationName Section Number. CS210 Exam #4 *** PLEASE TURN OFF ALL CELL PHONES*** Practice
Name Section Number CS210 Exam #4 *** PLEASE TURN OFF ALL CELL PHONES*** Practice All Sections Bob Wilson OPEN BOOK/OPEN NOTES You will have all 90 minutes until the start of the next class period. Spend
More informationA final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.
final A final variable is a variable which can be initialized once and cannot be changed later. The compiler makes sure that you can do it only once. A final variable is often declared with static keyword
More informationCS 3 Introduction to Software Engineering. 5: Iterators
CS 3 Introduction to Software Engineering 5: Iterators Questions? 2 PS1 Discussion Question You are to choose between two procedures, both of which compute the minimum value in an array of integers. One
More informationSoftware Construction
Lecture 2: Decomposition and Java Methods Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering
More informationFirst IS-A Relationship: Inheritance
First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class
More informationCPS 506 Comparative Programming Languages. Programming Language
CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support
More informationInheritance 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
More informationChapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited
Chapter 13 Abstract Classes and Interfaces Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations You have learned how to write simple programs
More informationCollections and Iterators. Collections
Collections and Iterators Based on the notes from David Fernandez-Baca and Steve Kautz Based on The Java Tutorial (http://docs.oracle.com/javase/tutorial/java/) Bryn Mawr College CS206 Intro to Data Structures
More informationCOS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism
COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism Ibrahim Albluwi Composition A GuitarString has a RingBuffer. A MarkovModel has a Symbol Table. A Symbol Table has a Binary
More informationLecture 2: Java & Javadoc
Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block
More informationConformance. Object-Oriented Programming Spring 2015
Conformance Object-Oriented Programming 236703 Spring 2015 1 What s Conformance? Overriding: replace method body in sub-class Polymorphism: subclass is usable wherever superclass is usable Dynamic Binding:
More informationExample: Count of Points
Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;
More information