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

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

The class Object. Lecture CS1122 Summer 2008

Java Fundamentals (II)

Introduction to Object-Oriented Programming

java.lang.object: Equality

INHERITANCE. Spring 2019

CSE 331 Spring 2018 Midterm

Building Java Programs. Inheritance and Polymorphism

Expected properties of equality

CSE 331 Software Design & Implementation

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

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

Inheritance (Part 5) Odds and ends

Methods Common to all Classes

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

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

Equality. Michael Ernst. CSE 331 University of Washington

CSE 331 Software Design & Implementation

MIT EECS Michael Ernst Saman Amarasinghe

Creating an Immutable Class. Based on slides by Prof. Burton Ma

CLASS DESIGN. Objectives MODULE 4

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

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

JAVA MOCK TEST JAVA MOCK TEST II

For this section, we will implement a class with only non-static features, that represents a rectangle

Outline. applications of hashing equality and comparisons in Java sorting selection sort bubble sort insertion sort

Chapter 11: Collections and Maps

Software Construction

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

Implementing Object Equivalence in Java Using the Template Method Design Pattern

Abstract Classes and Interfaces

C12a: The Object Superclass and Selected Methods

Inheritance. Transitivity

Equality. Michael Ernst. CSE 331 University of Washington

Super-Classes and sub-classes

Programming Languages and Techniques (CIS120)

Domain-Driven Design Activity

Principles of Software Construction: Objects, Design, and Concurrency. Testing and Object Methods in Java. Josh Bloch Charlie Garrod Darya Melicher

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Java Magistère BFA

CMSC 132: Object-Oriented Programming II

equals() in the class Object

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

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017

Java Classes, Inheritance, and Interfaces

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

public static boolean isoutside(int min, int max, int value)

Introduction to Inheritance

Inheritance (Part 2) Notes Chapter 6

CS11 Java. Winter Lecture 8

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Introduction to Programming Using Java (98-388)

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

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Exam 2 CSCI 2600 Principles of Software November 3, 2015

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

INSTRUCTIONS TO CANDIDATES

CS-202 Introduction to Object Oriented Programming

CSC Java Programming, Fall Java Data Types and Control Constructs

Programming Languages and Techniques (CIS120)

Defective Java Code: Turning WTF code into a learning experience

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

CS 2340 Objects and Design - Scala

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

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

Java Persistence API (JPA) Entities

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

JSR-305: Annotations for Software Defect Detection

Java Enum Java, winter semester ,2018 1

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

Defective Java Code: Turning WTF code into a learning experience

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

Lecture 18 CSE11 Fall 2013 Inheritance

CS260 Intro to Java & Android 03.Java Language Basics

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

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

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Programming Languages and Techniques (CIS120e)

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Java: advanced object-oriented features

Rules and syntax for inheritance. The boring stuff

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

1 Shyam sir JAVA Notes

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

From C++ to Java. Duke CPS

Announcements/Follow-ups

Language Features. 1. The primitive types int, double, and boolean are part of the AP

The Java Type System (continued)

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

Abstract and final classes [Horstmann, pp ] An abstract class is kind of a cross between a class and an interface.

Java Object Oriented Design. CSC207 Fall 2014

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

Java Overview An introduction to the Java Programming Language

Class, Variable, Constructor, Object, Method Questions

PIC 20A Number, Autoboxing, and Unboxing

JAVA MOCK TEST JAVA MOCK TEST III

ITI Introduction to Computing II

Transcription:

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 to established principles. When creating a class for general-purpose use, you must include definitions for No argument constructor Object Equality String representation Cloning Serialization Hashing These items take additional work, but the reward is robust, maintainable and reusable code. 1

Default Behavior Every Java object inherits a set of base methods from java.lang.object that every client can use. Each method has a sensible default behavior that can be overridden in the subclasses (except for final methods, marked above with F ). No Argument Constructor Java only provides us with the default (no-arg) constructor when we do not define any constructor for that class on our own. Remember that Canonical form is for purpose of general reuse. It makes your class more flexible especially if you also provide methods to set any parameters. Java adds the no arg constructor behind the scenes. 2

Object Equality The Java super class java.lang.object defines public boolean equals(object obj) Checks if some other object passed to it as an argument is equal to the object on which this method is invoked. x == y (Identity) tests whether x and y are two references to the same object. x.equals(y) tests whether x and y reference two objects with equal contents. Default implementation in object class simply tests for identify. Each class should define what it means by equals. 5 Put another way: == returns true, if the variable reference points to the same object in memory. This is called shallow comparison. The equals() method calls the user implemented equals() method, which compares the object attribute values. The equals() method provides deep comparison by checking if two objects are logically equal. If equals() method is not overriden, the default is used and object.equals() works just like the "==" operator. 6 3

What is the output? True False Explanation: equals is overridden. Because the argument passed to equals is of type Foo, the equals function on line 20 gets called and the value false is returned. Does the answer change if line 5 reads: Foo foo2 = new Foo(1);?? Test.java 7 Javadocs Equal() Reflexive An object must always be equal to itself; i.e., a.equals(a) Symmetric If two objects are equal, then they should be equal in both directions; i.e., if a.equals(b), then b.equals(a) Transitive If an object is equal to two others, then they must both be equal; i.e., if a.equals(b) and b.equals(c), then a.equals(c) Non-null An object can never be equal to null; i.e., a.equals(null) is always false 4

The Equals Method should Compare public class Point { private static double version = 1.0; private transient double distance; private int x, y; public boolean equals(object other) { if (other == this) return true; if (other == null) return false; if (getclass()!= other.getclass()) return false; Point point = (Point)other; return (x == point.x && y == point.y); } } If the argument is this; return true (reflexivity) If the argument is null return false (non-null) If the argument is of a different type return false (symmetry) https://www.youtube.c om/watch?v=7v3589 CReug Another Example 5

Now look at this code What is the output? True False Let s override the equals method instead! More Code What is the output? True False 6

Implementing the HashCode() Function If a class overrides equals, it must override hashcode When they are both overridden, equals and hashcode must use the same set of fields If two objects are equal, then their hashcode values must be equal as well If the object is immutable, then hashcode is a candidate for caching and lazy initialization The hashcode method defined by class Object usually returns distinct integers for distinct objects. Typically implemented by converting the internal address of the object into an integer. (JVM dependent) http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml 13 14 7

Calculating hashcode() Include a prime number. Involve significant variables of your object including those used in the equals operation. byte, char, short or int, then var_code = (int)var; long, then var_code = (int)(var ^ (var >>> 32)); float, then var_code = Float.floatToIntBits(var); double, then long bits = Double.doubleToLongBits(var); var_code = (int)(bits ^ (bits >>> 32)); boolean, then var_code = var? 1 : 0; object reference var_code = (null == var? 0 : var.hashcode()); 15 Calculating hashcode() Combine this individual variable hash code var_code in the original hash code hash as follows - hash = 31 * hash + var_code; Follow these steps for all the significant variables and in the end return the resulting integer hash. Check that the hashcode() method: 1. Returns equal hashcodes for equal objects. 2. Hash codes returned for the object are consistently the same for multiple invocations during the same execution. 16 8

What is the output? True False What is the output? True False 17 Override hashcode() In java we must modify equals and hashcode together! Uses a prime number to get a good distribution at low runtime cost. 18 9

Defining equals in terms of Mutable Fields What if we hadn t defined equals in terms of immutable (final) fields? What might happen if an object was placed into a hash bucket and then its values were changed??? Mistakes like this create hard to fix bugs!! Try to avoid them by following good practices. 19 tostring() Returns a string representation of the object that "textually represents" the object. The result should be a concise but informative representation that is easy for a person to read. class Vec { Vec() { } Vec(double xx, double yy) { x = xx; y = yy; } double x, y; } return "X: " + Double.toString(x) + ", Y: " + Double.toString(y); 20 10