Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]

Slides:



Advertisements
Similar presentations
Identity and Equality Based on material by Michael Ernst, University of Washington.
Advertisements

Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Programo Issues Cora Pérez Ariza ~ DECSAI ~ UGR Granada, January 28 th & 29 th, 2009.
Effective Java, Chapter 3: Methods Common to All Objects.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Effective Java, Chapter 3: Methods Common to All Objects Paul Ammann.
Equality Programming in C# Equality CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Searching and Sorting I 1 Searching and Sorting 1.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
Not overriding equals  what happens if you do not override equals for a value type class?  all of the Java collections will fail in confusing ways 1.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.
Goals for Today 1  Multiton  maps  static factory methods.
Mixing Static and Non-static
Inheritance (Part 4) Polymorphism and Abstract Classes 1.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Overriding toString()
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Symbol Tables From “Algorithms” (4 th Ed.) by R. Sedgewick and K. Wayne.
1  lecture slides online
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
Java Type System and Object Model Horstmann ch , 7.7.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
Composition  recall that an object of type X that is composed of an object of type Y means  X has-a Y object and  X owns the Y object  in other words.
Composition 1.  recall that an object of type X that is composed of an object of type Y means  X has-a Y object and  X owns the Y object  in other.
Mixing Static and Non-static Singleton 1. Singleton Pattern 2  “There can be only one.”  Connor MacLeod, Highlander.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
COMP 110 Some notes on inheritance, review Luv Kohli December 1, 2008 MWF 2-2:50 pm Sitterson 014.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
More constructors 1. Constructors  recall that a public constructor is what a client uses to create an object  the purpose of a constructor is to initialize.
1 clone() Defined in Object Creates an identical copy –Copies pointers to fields (does not copy fields of fields) –Makes a shallow copy if the object’s.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
More on Objects Static and equals.. Each object takes memory Each time you make an object of a given class – you create a space in memory. E.g. public.
Searching.
CompareTo.
Lecture 17: Polymorphism (Part II)
CS 302 Week 11 Jim Williams, PhD.
COMP 110 Some notes on inheritance, review
Non-static classes.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Testing, cont., Equality and Identity
slides created by Ethan Apter
slides created by Ethan Apter
Searching.
CS/ENGRD 2110 Spring 2019 Lecture 6: Consequence of type, casting; function equals
slides created by Ethan Apter and Marty Stepp
Review for Midterm 3.
Chapter 7 Java Object Model
Presentation transcript:

Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[] args) { Enigma e = new Enigma(); System.out.println( e.equals(e) ); }  You must not override Object.equals() [Java Puzzlers by Joshua Block and Neal Gaffer]

Goals  finish implementing the immutable class PhoneNumber  constructor  equals() 2

Constructors 3  constructors are responsible for initializing instances of a class  a constructor declaration looks a little bit like a method declaration:  the name of a constructor is the same as the class name  a constructor may have an access modifier (but no other modifiers)  every constructor has an implicit this parameter  a constructor will often need to validate its arguments  because you generally should avoid creating objects with invalid state [notes 2.2.3], [AJ 4.4]

4 public final class PhoneNumber { // version 4; see versions 1, 2, and 3 for attributes and methods public PhoneNumber(int areaCode, int exchangeCode, int stationCode) { rangeCheck(areaCode, 999, "area code"); rangeCheck(exchangeCode, 999, "exchange code"); rangeCheck(stationCode, 9999, "station code"); this.areaCode = (short) areaCode; this.exchangeCode = (short) exchangeCode; this.stationCode = (short) stationCode; } parameter names shadow attribute names

5 private static void rangeCheck(int num, int max, String name) { if (num max) { throw new IllegalArgumentException(name + " : " + num); }

Constructor Overloading 6  note that you can overload constructors // in PhoneNumber class; exercises for the student public PhoneNumber(String areaCode, String exchangeCode, String stationCode) { } public PhoneNumber(String phoneNum) { // assume phoneNum looks like (AAA) BBB-CCCC }

Copy Constructor 7  the copy constructor is a notable overload  for a class X the copy constructor looks like public X(X x)  a copy constructor creates an object by copying another object of the same type  you don't need (and should not declare) a copy constructor for immutable types [AJ p ]

Overriding equals() 8  suppose you write a value class that extends Object but you do not override equals()  what happens when a client tries to use equals() ?  Object.equals() is called // PhoneNumber client PhoneNumber cse = new PhoneNumber(416, 736, 5053); System.out.println( cse.equals(cse) ); // true PhoneNumber cseToo = cse; System.out.println( cseToo.equals(cse) ); // true PhoneNumber cseAlso = new PhoneNumber(416, 736, 5053); System.out.println( cseAlso.equals(cse) ); // false [notes 2.2.4], [AJ p ]

9 64 client cse cseToo cseAlso 600PhoneNumber object areaCode 416 exchangeCode 736 stationCode PhoneNumber object areaCode 416 exchangeCode 736 stationCode

Object.equals() 10  implements an identity check  an instance is equal only to itself  x.equals(y) is true if and only if x and y are references to the same object  most value classes should support logical equality  an instance is equal to another instance if their states are equal  e.g. two PhoneNumbers are equal if their area, exchange, and station codes have the same values

11  implementing equals() is surprisingly hard  "One would expect that overriding equals(), since it is a fairly common task, should be a piece of cake. The reality is far from that. There is an amazing amount of disagreement in the Java community regarding correct implementation of equals(). Look into the best Java source code or open an arbitrary Java textbook and take a look at what you find. Chances are good that you will find several different approaches and a variety of recommendations."  Angelika Langer, Secrets of equals() – Part 1   what we are about to do does not always produce the result you might be looking for  but it is always satisfies the equals() contract  and it's what the notes and textbook do

An Instance is Equal to Itself 12  x.equals(x) should always be true  also, x.equals(y) should always be true if x and y are references to the same object  you can check if two references are equal using ==

PhoneNumber.equals() : Part 1 13 // inside class public boolean equals(Object obj) { boolean eq = true; if (this == obj) eq = true; return eq; }

An Instance is Never Equal to null 14  Java requires that x.equals(null) returns false  you must not throw an exception if the argument is null  so it looks like we have to check for a null argument...

PhoneNumber.equals() : Part 2 public boolean equals(Object obj) { boolean eq = true; if (this == obj) eq = true; else if (obj == null) eq = false; return eq; }

Instances of the Same Type can be Equal 16  the implementation of equals() used in the notes and the textbook is based on the rule that an instance can only be equal to another instance of the same type  at first glance, this sounds reasonable and is easy to implement using Object.getClass() public final Class getClass()  Returns the runtime class of an object.

PhoneNumber.equals() : Part 3 public boolean equals(Object obj) { boolean eq = true; if (this == obj) eq = true; else if (obj == null) eq = false; else if (this.getClass() != obj.getClass()) eq = false; return eq; }

Instances with Same State are Equal 18  recall that the value of the attributes of an object define the state of the object  two instances are equal if all of their attributes are equal  recipe for checking equality of attributes 1. if the attribute type is a primitive type other than float or double use == 2. if the attribute type is float use Float.compare() 3. if the attribute type is double use Double.compare() 4. if the attribute is an array consider Arrays.equals() 5. if the attribute is a reference type use equals(), but beware of attributes that might be null

PhoneNumber.equals() : Part 4 public boolean equals(Object obj) { boolean eq = true; if (this == obj) eq = true; else if (obj == null) eq = false; else if (this.getClass() != obj.getClass()) eq = false; else { PhoneNumber other = (PhoneNumber) obj; eq = (this.areaCode == other.areaCode && this.exchangeCode == other.exchangeCode && this.stationCode == other.stationCode); } return eq; }

The equals() Contract Part 1 20  for reference values equals() is 1. reflexive :  an object is equal to itself  x.equals(x) is true 2. symmetric :  two objects must agree on whether they are equal  x.equals(y) is true if and only if y.equals(x) is true 3. transitive :  if a first object is equal to a second, and the second object is equal to a third, then the first object must be equal to the third  if x.equals(y) is true, and y.equals(z) is true, then x.equals(z) must be true

The equals() Contract Part consistent :  repeatedly comparing two objects yields the same result (assuming the state of the objects does not change) 5. x.equals(null) is always false