Implementing Object Equivalence in Java Using the Template Method Design Pattern

Size: px
Start display at page:

Download "Implementing Object Equivalence in Java Using the Template Method Design Pattern"

Transcription

1 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 {stevende, Abstract A standard practice in object-oriented programming is to implement an operation, called equals in Java, for testing the equality of two objects. The equals method should be defined for every new Java class, but because of the intricacies of inheritance, casting, and dynamic typing, equals is often quite difficult to write correctly. And unfortunately many textbooks present flawed implementations of this operation. In this paper, we present a semantically correct technique for testing object equivalence, a technique that simultaneously brings together important mathematical foundations (equivalence relations), practical programming issues (inheritance, casting, dynamic typing), and sound software design (design patterns) in a natural and compelling way. While Java is used to demonstrate how the semantic flaws are corrected and the design improved using our techniques, the design is general enough that it will be clear how the same ideas could easily be extended to other languages such as C++. 1 Introduction An increasingly common design tool for the practicing software designer is the framework, since frameworks allow programmers to write applications that easily leverage code written by others. For example the GUI Applet framework gives programmers the ability to perform complex graphical operations without ever opening a window, while data structure frameworks such as the Java Collections Framework (JCF) and the Standard Template Library (STL) allow programmers to use complex sets, linked lists, and trees without having to worry about the data structure implementation details. Of course, frameworks also come with expectations on the objects they manipulate. For example, both the JCF and STL expect that testing for object equality be implemented as an equivalence relation, and failure to do so can cause Sets to contain duplicate values. Such errors are notoriously difficult to find, even for experienced programmers. And to make matters worse, textbooks often present flawed versions of these critical operations. In this paper, we present a way of using design patterns to ensure that framework requirements are met. In particular, we focus on testing for object equality. Note, however, that similar arguments can also be made for comparison. Our main point here is twofold: first, that there is a semantically right way to test for equality of objects, and second that such a design easily admits (in fact, almost demands) the use of the Template Method design pattern. Our purpose over the next few sections is to develop a design, based on the Template Method design pattern [4], for testing object equality that simultaneously maximizes code reuse, encapsulation, and data hiding, and minimizes semantic errors. We begin by considering a typical, but flawed, beginner s implementation of object equality. We then show how even in this most simple and fundamental of examples, the Template Method design pattern is an easy design solution that corrects these flaws. We present our ideas in Java, but the generality of our design also makes it easily transferable to C++. 2 Testing for Equality using the Template Method Design Pattern For our discussions that follow, we assume the existence of a base class A containing, for simplicity, just a single private data member that would be properly initialized by a default constructor (which we do not show). Given this definition, consider the beginner s implementation of the simple, but flawed, equals member function shown below: Beginner s implementation of equals class A { public boolean equals(a that) { return (this.x == that.x);

2 As a teaching tool, this example is a universal favorite because it forces new Java developers to carefully confront their understanding of the apparent versus actual types of objects when they attempt to use this method in a code fragment such as the one that follows. For this and subsequent examples, assume that the default constructor sets x to some value. Attempting to use equals from class A, but invoking equals from Object instead Object instance1 = new A(); Object instance2 = new A(); if (instance1.equals(instance2) { // should be equal, but won t be! Of course, in order to force the Java virtual machine to correctly select the equals method provided by class A (versus that provided by the class Object), the argument type defined in the signature for equals must be Object, and that s usually the point of emphasis when teaching new Java programmers. While our example is tailored to make this point, Java programmers will experience this error in practice when comparing Objects extracted from a Vector or any of the collections in the JCF. Either way, the end result is the same the wrong code will be executed. But the story hardly ends there. There is in fact a right way ([2], [3], [5]), and a number of wrong ways, to write the entire equals member function. In fact, there are hundreds of examples in the standard Java library containing flawed implementations of equals. What criteria should a properly constructed equals method satisfy? There are three critical criteria (in fact, there are more than three criteria, but we ll focus on just these three): 1 equals must have the signature exactly as follows: boolean equals(object). 2 equals must return false if its argument is null. 3 equals must be an equivalence relation, meaning that it satisfies 3.1 Reflexivity: a.equals(a) must be true. 3.2 Symmetry: If a.equals(b) then b.equals(a). 3.3 Transitivity: If a.equals(b) and b.equals(c) then a.equals(c). Given these criteria, the following implementation involving a new super class T and the original class A, which is now a sub class of T, properly satisfies these requirements: Equals and localequals using a super class T abstract class T { public final boolean equals(object that) { if ((that!= null) && (that instanceof T)) { T castedthat = (T) that; if (this.gettypeequiv().equals( castedthat.gettypeequiv())) { isequal = localequals(that); return true; // to stop the chaining abstract protected Class gettypeequiv(); class A extends T { A castedthat = (A) that; boolean isequal = (this.x == castedthat.x); return (isequal && super.localequals(that)); protected Class gettypeequiv() { Class result = null; try { // will never fail, but must try/catch result = Class.forName( A ); catch (ClassNotFoundExeception e) { return result; Notice that our implementation factors out the actual private data member comparisons into a new protected mode helper function that we ve called localequals. Doing so results in an implementation of equals that is independent of any specific class, and so we have moved it into the abstract super class called T. Hence, our form of equals is invariant with respect to class, and so can be inherited by all sub classes of T without modification! And that s why we made it public and final. Also of note is that the only way for two instances to be equal is if their corresponding types are the same, and if they both inherit from the super class T. From a software design standpoint, we would argue that if two objects do not both inherit from T, their types shouldn t be considered equivalent, and so they would not be equal. Hence, each sub class will necessarily be required to supply a unique (and protected) version of localequals and of gettypeequiv in order to make the proper private data member comparisons and to report the appropriate class type, respectively. If we now extend the class A with a sub class B also containing (again for simplicity) a single private data member y, here would be the versions of localequals and

3 gettypeequiv for class B, assuming that we do not wish for A and B to be of the same type: LocalEquals and gettypeequiv for class B class B extends A { B castedthat = (B) that; boolean isequal = (this.y == castedthat.y); return (isequal && super.localequals(that)); protected Class gettypeequiv() { Class result = null; try { // will never fail, but must try/catch result = Class.forName( B ); catch (ClassNotFoundExeception e) { return result; private int y; Notice that our skeletal design for localequals differs for each class in two areas only. First, each class requires a specific downcast of the argument into the appropriate class type (e.g., B castedthat = (B) that). This cast is type safe because the actual types of both this and that are previously checked and guaranteed to be the same by the calls to gettypeequiv in the equals method of our super class T. At the moment, gettypeequiv simply returns the appropriate actual types using Class.forName for each separate class, but we ll revisit this particular issue later to handle a more general situation (and also explain why we did not use getclass or instanceof here instead). Second, each class must provide for the specific comparisons of the private data members for that class. Note that the skeletal design we have provided explicitly chains to the super class for any local comparisons required there as well. Hence, we avoid any need for accessors or (worse) for direct access to super class data members. This design nicely enforces encapsulation, data hiding, and code reuse. Figure 1 shows the UML for our new design: - x : int A -y :int T + equals(object that) : boolean B Figure 1: Template Method Design for equals We ve really done nothing more than apply the Template Method design pattern [4] to testing object equivalence while guaranteeing that the code also satisfies the general contract for equivalence relations. The template in this case is our class T with its equals method since it supplies the invariant steps required to correctly implement equality. The variant code is supplied by each sub class in localequals and gettypeequiv, and we have even provided a basic skeletal outline for each such method. 3 Some Common Design Errors We also wish to point out that many versions of equals do not guarantee that equals implements an equivalence relation. Specifically, the symmetry requirement of criteria 3.2 is often unsatisfied. Here is a variation of the suspect code that can be found in almost any Java programming text and in many Java library routines: Equals using instanceof for classes A and B class A { public boolean equals(object that) { if ((that!= null) && (that instanceof A)) { A castedthat = (A) that; isequal = (this.x == castedthat.x); class B extends A { public boolean equals(object that) { if ((that!= null) && (that instanceof B)) { B castedthat = (B) that; isequal = (this.y == castedthat.y); return (isequal && super.equals(that)); private int y; Note that the equals method is overridden in each class and sub class since the use of the cast testing operator instanceof requires a specific type to test. The problem with this version (aside from the duplicated code) is highlighted by the following code segment, which shows the failure in the symmetry requirement (see also [1], [2], [3], and [5]): Failure of symmetry requirement using instanceof Object instancea = new A(); Object instanceb = new B(); if ((instancea.equals(instanceb)) == (instanceb.equals(instancea))) { // should be true, but will be false! While instanceb is an instanceof class B and therefore of class A, instancea is not an instanceof class B. So,

4 instancea.equals(instanceb) would return true, but instanceb.equals(instancea) would fail the instanceof test and return false. Our solution corrects that deficiency by using Class.forName inside of gettypeequiv to retrieve the actual type of the arguments instead of using the cast testing instanceof operator. At the same time we move the variant type-casting code into the localequals functions for each class. A 1 A 2 T B 2 B 1 B 4 4 Defining Type Equivalence for Classes In our Template Method design, each class specific implementation of localequals requires a specific downcast of the argument into the appropriate type, and as described earlier this cast is type safe because the actual types of both this and that are previously checked and guaranteed to be the same by the use of Class.forName in the code for gettypeequiv. Obviously if this and that are of the same class, then they are of identical type, and this is a key to why our design correctly adheres to the general contract for equivalence relations (in particular, the symmetry and transitivity requirements). What if one wanted to define a set of two or more different classes all of which should be treated as the same type? For example, it might be desirable to extend class A with class B in such a way as to permit overriding of some of the methods of A, but still maintain identical private data members. Or more generally, it might be desirable to simply define two different classes A and B both of which inherit from a common ancestor C, neither of which inherits from the other, and yet consider A and B to be equivalent types for the purposes of comparison. We call this concept type equivalence. In either case our design permits these generalizations as long you adhere to the following simple rules: 1. All classes that are in the same type equivalence set E must have a common ancestor R E in the inheritance hierarchy, and R E also must be in the set E. Hence, R E is the canonical member for the type equivalent classes in E. 2. The template class T must be a proper ancestor of R E in the inheritance hierarchy. 3. R E must be the only member of the type equivalence set E to define gettypeequiv and localequals. All other members of E will therefore inherit these methods from R E. 4. If A and B are both members of the type equivalence set E, then all classes between A and B in the inheritance hierarchy must also be in E. As an example of how these rules will permit a variety of designs of type equivalence while maintaining semantic correctness, encapsulation, and code reuse, consider the example inheritance hierarchy shown in Figure 2. B 3 Figure 2: A Type Equivalence Inheritance Hierarchy Figure 2 shows three distinct type equivalence sets: A = {A 1, A 2, B = {B 1, B 2, B 3, B 4, and C = {C 1. Each type equivalence set has a top-most member (i.e. the canonical member R E ) of the inheritance hierarchy: these are A 1 for A, B 1 for B, and C 1 for C in this example. Each of these is therefore required to define a version of localequals and of gettypeequiv, but none of the other members of the inheritance hierarchy in this example would contain such methods. In particular, the sub classes B 2, B 3, and B 4 would all inherit localequals and gettypeequiv from B 1 since they are all in the same type equivalence set as B 1. Using this design allows two instances of the type equivalence set B to be tested for equality based only on the private data members of B 1. The fact that the two distinct instances may not be of the same actual Java type is of no consequence here since the downcast from an Object to a B 1 performed in localequals is still type safe (as guaranteed by gettypeequiv). And of course the semantic correctness of equals is still maintained by our Template Method design. As a concluding remark on the design and implementation of equals with respect to type equivalence, if you take the position that each distinct class should define its own distinct type equivalence set (and the authors do indeed take this position), then the design is greatly simplified. In this case, gettypeequiv would be moved into the template class T and made private and final as shown below. Ensuring that no two distinct classes are type equivalent abstract class T {... // same as before C 1 private final Class gettypeequiv() { return this.getclass(); In this way, each class identifies itself (using getclass) as distinct from all other classes, and there is no need or way for any class to ever override gettypeequiv. 5 Transferability of the Design Pattern to C++ One test of the value and generality of a good design is whether the same design is cleanly transferable to a different object-oriented language. In the case of our equals design and C++, we are interested in the overloading of the operator==.

5 Many of the same design and implementation issues we considered in Java are also issues in C++, namely providing the proper signatures, testing the argument for null, ensuring this and that are type equivalent and then performing the corresponding downcast, and most importantly, ensuring that the operation actually implements an equivalence relation. In each case, there is a simple, but not always elegant, C++ solution. As an example, here would be the C++ versions of the template base class T and the sub class A from section 2 above, but now implemented in C++. C++ versions of classes T and A class T { public: bool operator==(const T &that) const { bool isequal = false; if ((&that!= NULL) && (*(this->gettypeequiv()) == *(that.gettypeequiv()))) { isequal = (this->localequals(&that)); protected: virtual bool localequals(const T *that) const { return true; // default to stop the chaining ; virtual const type_info* gettypeequiv() const = 0; class A : public T { protected: virtual bool localequals(const T *that) const { const A *castedthat = dynamic_cast<const A*>(that); bool isequal = (this->x == castedthat->x); return (isequal && T::localEquals(that)); 6 Summary We have presented a semantically correct software design solution for testing object equivalence using the Template Method design pattern. But we have done considerably more as well. We have taken this simple but important example and demonstrated how identifying variant and invariant behavior can be the key to code reuse and the proper implementation of equality. We have demonstrated how to use dynamic typing and inheritance to properly chain sub class methods to their super classes in order to obtain the correct semantic behavior. We have shown how to satisfy the general contract for equivalence relations, provide for flexible definitions of type equivalence, and yet not require any code duplication. And we have highlighted the importance of defining the proper method signatures in order to obtain the desired dynamic method invocation behavior. References [1] Bergin, J. Canonical Form of a Java Class. ml. [2] Bloch, J. Effective Java Programming Language Guide. Addison-Wesley (2001). [3] Cohen, T. How Do I Correctly Implement the equals() Method? Dr. Dobb s Journal, May (2002). [4] Gamma, E., Helm, R., Johnson, R., and Vlissides, J. Design Patterns: Elements of Reuseable Object- Oriented Software. Addison-Wesley Publishing (1995). [5] Horstmann, C., and Cornell, G. Core Java 2: Volume I Fundamentals. Sun Microsystems Press (2001). [6] Stevenson, D.E., and Phillips, A.T. A Template Design for Correctly Overriding the Operator== in C++. UW- Eau Claire Computer Science Technical Report, August (2002). virtual const type_info* gettypeequiv() const { return &typeid(*(new A())); private: int x; ; The design similarities between the C++ version and our Java version are intentional and apparent. The only significant change in the design of the code (ignoring the obvious syntax and implementation specific details of type casting) is that the C++ version of operator== requires the template type T to be the argument in the signature, since C++ has no overarching Object. This also permits us to drop the explicit that instanceof T inheritance check since this type compatibility test is required for compilation anyway. Aside from this, the generality of our design makes it easily transferable to C++. For a complete discussion about these and many more issues in the C++ implementation of operator==, see [6].

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

Canonical 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 information

Methods Common to all Classes

Methods Common to all Classes Methods Common to all Classes 9-2-2013 OOP concepts Overloading vs. Overriding Use of this. and this(); use of super. and super() Methods common to all classes: tostring(), equals(), hashcode() HW#1 posted;

More information

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

Graphical 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 information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L 10.1 10.3 1 Interface Hierarchies Inheritance can

More information

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding Conformance Conformance and Class Invariants Same or Better Principle Access Conformance Contract Conformance Signature Conformance Co-, Contra- and No-Variance Overloading and Overriding Inheritance as

More information

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

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

More information

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals CS/ENGRD 2110 FALL 2018 Lecture 6: Consequence of type, casting; function equals http://courses.cs.cornell.edu/cs2110 Overview references in 2 Quick look at arrays: array Casting among classes cast, object-casting

More information

CSE 401/M501 Compilers

CSE 401/M501 Compilers CSE 401/M501 Compilers ASTs, Modularity, and the Visitor Pattern Hal Perkins Autumn 2018 UW CSE 401/M501 Autumn 2018 H-1 Agenda Today: AST operations: modularity and encapsulation Visitor pattern: basic

More information

Java Fundamentals (II)

Java 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 information

Super-Classes and sub-classes

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

More information

Expected properties of equality

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??

More information

CSE 331 Software Design & Implementation

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

More information

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Introduction to Object-Oriented Programming

Introduction 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 information

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Course Overview This course teaches programmers the skills necessary to create Java programming system applications and satisfies the

More information

CSE 331 Software Design & Implementation

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

More information

Patterns for polymorphic operations

Patterns for polymorphic operations Patterns for polymorphic operations Three small object structural patterns for dealing with polymorphism Alexander A. Horoshilov hor@epsylontech.com Abstract Polymorphism is one of the main elements of

More information

Software Construction

Software Construction 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

More information

Part 3. Why do we need both of them? The object-oriented programming paradigm (OOP) Two kinds of object. Important Special Kinds of Member Function

Part 3. Why do we need both of them? The object-oriented programming paradigm (OOP) Two kinds of object. Important Special Kinds of Member Function Part 3 The object-oriented programming paradigm (OOP) Two kinds of object Value objects The object contains the member data items Allocated automatically just like primitive (built-in) data items Suitable

More information

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss 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 information

Introduction to Programming Using Java (98-388)

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;

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

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 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 information

Building Java Programs. Inheritance and Polymorphism

Building Java Programs. Inheritance and Polymorphism Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Autumn 2009 10/20/2009 2002-09 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 30, 2016 Collections and Equality Chapter 26 Announcements Dr. Steve Zdancewic is guest lecturing today He teaches CIS 120 in the Fall Midterm

More information

Item 4: Extensible Templates: Via Inheritance or Traits?

Item 4: Extensible Templates: Via Inheritance or Traits? ITEM1_11new.fm Page 1 Tuesday, November 27, 2001 12:49 PM Item 4: Extensible Templates: Via Inheritance or Traits?. ITEM 4: EXTENSIBLE TEMPLATES: VIA INHERITANCE OR TRAITS? DIFFICULTY: 7 This Item reviews

More information

Outline. Logistics. Logistics. Principles of Software (CSCI 2600) Spring Logistics csci2600/

Outline. Logistics. Logistics. Principles of Software (CSCI 2600) Spring Logistics  csci2600/ Outline Principles of Software (CSCI 600) Spring 018 http://www.cs.rpi.edu/academics/courses/spring18/csci600/ Konstantin Kuzmin, kuzmik@cs.rpi.edu Office hours: Monday and Thursday 4:00 pm - 5:30 pm Mailing

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

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

Polymorphism. 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 information

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

Outline. 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 information

Inheritance -- Introduction

Inheritance -- Introduction Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

Comp 249 Programming Methodology

Comp 249 Programming Methodology Comp 249 Programming Methodology Chapter 7 Inheritance- Part B Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,

More information

Comp 249 Programming Methodology Chapter 8 - Polymorphism

Comp 249 Programming Methodology Chapter 8 - Polymorphism Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified

More information

ITI Introduction to Computing II

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

More information

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 1. Introduction 2. Objects and classes 3. Information hiding 4. Constructors 5. Some examples of Java classes 6. Inheritance revisited 7. The class hierarchy

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

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

Inheritance. 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 information

Programming II (CS300)

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

More information

The Java Type System (continued)

The Java Type System (continued) Object-Oriented Design Lecture 5 CSU 370 Fall 2007 (Pucella) Friday, Sep 21, 2007 The Java Type System (continued) The Object Class All classes subclass the Object class. (By default, this is the superclass

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

CS-202 Introduction to Object Oriented Programming

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

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Winter 2008 1/22/2008 2002-08 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

Safety SPL/2010 SPL/20 1

Safety SPL/2010 SPL/20 1 Safety 1 system designing for concurrent execution environments system: collection of objects and their interactions system properties: Safety - nothing bad ever happens Liveness - anything ever happens

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

4 CoffeeStrainer Virtues and Limitations

4 CoffeeStrainer Virtues and Limitations In this chapter, we explain CoffeeStrainer s virtues and limitations and the design decisions that led to them. To illustrate the points we want to make, we contrast CoffeeStrainer with a hypothetical,

More information

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

The 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 information

Late-bound Pragmatical Class Methods

Late-bound Pragmatical Class Methods Late-bound Pragmatical Class Methods AXEL SCHMOLITZKY, MARK EVERED, J. LESLIE KEEDY, GISELA MENGER Department of Computer Structures University of Ulm 89069 Ulm, Germany {axel, markev, keedy, gisela@informatik.uni-ulm.de

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Software Development (cs2500)

Software Development (cs2500) Software Development (cs2500) Lecture 31: Abstract Classes and Methods M.R.C. van Dongen January 12, 2011 Contents 1 Outline 1 2 Abstract Classes 1 3 Abstract Methods 3 4 The Object Class 4 4.1 Overriding

More information

ITI Introduction to Computing II

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

More information

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

More information

Chapter 5 Object-Oriented Programming

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

More information

Increases Program Structure which results in greater reliability. Polymorphism

Increases Program Structure which results in greater reliability. Polymorphism UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the

More information

Comp 249 Programming Methodology

Comp 249 Programming Methodology Comp 249 Programming Methodology Chapter 7 - Inheritance Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,

More information

CSE 331 Spring 2018 Midterm

CSE 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 information

Making New instances of Classes

Making New instances of Classes Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using

More information

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals 1 CS/ENGRD 2110 FALL 2017 Lecture 6: Consequence of type, casting; function equals http://courses.cs.cornell.edu/cs2110 Overview ref in JavaHyperText 2 Quick look at arrays array Casting among classes

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. 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 information

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

Data 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 information

DESIGN PATTERN - INTERVIEW QUESTIONS

DESIGN PATTERN - INTERVIEW QUESTIONS DESIGN PATTERN - INTERVIEW QUESTIONS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Design Pattern Interview Questions

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

B16 Object Oriented Programming

B16 Object Oriented Programming B16 Object Oriented Programming Michael A. Osborne mosb@robots.ox.ac.uk http://www.robots.ox.ac.uk/~mosb/teaching.html#b16 Hilary 2013 This course will introduce object-oriented programming (OOP). It will

More information

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017 Programming Language Concepts Object-Oriented Programming Janyl Jumadinova 28 February, 2017 Three Properties of Object-Oriented Languages: Encapsulation Inheritance Dynamic method binding (polymorphism)

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass Inheritance and Polymorphism Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism Inheritance (semantics) We now have two classes that do essentially the same thing The fields are exactly

More information

C++ Programming: Polymorphism

C++ 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 information

Lecture 10. Overriding & Casting About

Lecture 10. Overriding & Casting About Lecture 10 Overriding & Casting About Announcements for This Lecture Readings Sections 4.2, 4.3 Prelim, March 8 th 7:30-9:30 Material up to next Tuesday Sample prelims from past years on course web page

More information

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson More on Design CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson Outline Additional Design-Related Topics Design Patterns Singleton Strategy Model View Controller Design by

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Equality. Michael Ernst. CSE 331 University of Washington

Equality. 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

CS/ENGRD 2110 SPRING 2018

CS/ENGRD 2110 SPRING 2018 1 The fattest knight at King Arthur's round table was Sir Cumference. He acquired his size from too much pi. CS/ENGRD 2110 SPRING 2018 Lecture 6: Consequence of type, casting; function equals http://courses.cs.cornell.edu/cs2110

More information

Inheritance and Polymorphism

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

More information

Wrapping a complex C++ library for Eiffel. FINAL REPORT July 1 st, 2005

Wrapping a complex C++ library for Eiffel. FINAL REPORT July 1 st, 2005 Wrapping a complex C++ library for Eiffel FINAL REPORT July 1 st, 2005 Semester project Student: Supervising Assistant: Supervising Professor: Simon Reinhard simonrei@student.ethz.ch Bernd Schoeller Bertrand

More information

Domain-Driven Design Activity

Domain-Driven Design Activity Domain-Driven Design Activity SWEN-261 Introduction to Software Engineering Department of Software Engineering Rochester Institute of Technology Entities and Value Objects are special types of objects

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming Goals of Lecture Lecture 27: OO Design Patterns Cover OO Design Patterns Background Examples Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2001 April 24, 2001 Kenneth

More information

CS558 Programming Languages Winter 2013 Lecture 8

CS558 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 information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

Equality for Abstract Data Types

Equality for Abstract Data Types Object-Oriented Design Lecture 4 CSU 370 Fall 2008 (Pucella) Tuesday, Sep 23, 2008 Equality for Abstract Data Types Every language has mechanisms for comparing values for equality, but it is often not

More information

25. Generic Programming

25. Generic Programming 25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and

More information

Exception Handling Alternatives (Part 2)

Exception Handling Alternatives (Part 2) Exception Handling Alternatives (Part 2) First published in Overload 31 Copyright 1999 Detlef Vollmann Resume In part 1, several alternative mechanisms for handling exceptional events were presented. One

More information

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

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

More information

Rules and syntax for inheritance. The boring stuff

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

More information

More On inheritance. What you can do in subclass regarding methods:

More On inheritance. What you can do in subclass regarding methods: More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature

More information

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

COURSE 2 DESIGN PATTERNS

COURSE 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 information