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.

Slides:



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

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.
== equals ? CSE 331 SOFTWARE DESIGN & IMPLEMENTATION EQUALITY Autumn 2011.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
CS102--Object Oriented Programming Lecture 8: – More about Inheritance When to use inheritance Relationship between classes Rules to follow Copyright ©
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.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
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.
More about inheritance Exploring polymorphism 5.0.
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.
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[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Implementation: Part 3 Software Construction Lecture 8.
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[]
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.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
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.
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.
Topic 4 Inheritance.
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.
More about inheritance Exploring polymorphism 5.0.
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 and Access Control CS 162 (Summer 2009)
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
Java Type System and Object Model Horstmann ch , 7.7.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Non-static classes 1.  a utility class has features (fields and methods) that are all static  all features belong to the class  therefore, you do not.
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.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance and Polymorphism
CSC142 NN 1 CSC 142 Overriding methods from the Object class: equals, toString.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
COMP 110 Some notes on inheritance, review Luv Kohli December 1, 2008 MWF 2-2:50 pm Sitterson 014.
Important Annoucement 1  I messed up something in the last class  if a subclass overrides a method that throws an exception then it must either 1. throw.
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.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Searching.
CSC 205 Java Programming II
COMP 110 Some notes on inheritance, review
Non-static classes.
Testing, cont., Equality and Identity
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Searching.
CS/ENGRD 2110 Spring 2019 Lecture 6: Consequence of type, casting; function equals
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Review for Midterm 3.
Presentation transcript:

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 object that was used to call the method 2

Accessors  an accessor method enables the client to gain access to an otherwise private field of the class  the name of an accessor method often begins with get  for fields of primitive type or immutable type, the accessor method implementation simply returns the value of the field  for fields that are object references the implementer must think more carefully about the implementation  this will be discussed later on in the course 3

4 public class Complex { private double real; private double imag; public Complex(double re, double im) { this.real = re; this.imag = im; } public double getReal() { return this.real; } public double getImag() { return this.imag; }

Mutators  a mutator method enables the client to modify (or mutate) an otherwise private field of the class  the name of an accessor method often begins with set  for fields of primitive type or immutable type, the mutator method implementation simply modifies the value of the field  for fields that are object references the implementer must think more carefully about the implementation  this will be discussed later on in the course 5

6 public void setReal(double newReal) { this.real = newReal; } public void setImag(double newImag) { this.imag = newImag; }

conj 7

8 public Complex conj() { return new Complex(this.getReal(), -this.getImag()); }

abs 9

10 public double abs() { // "obvious" implementation double a = this.getReal(); double b = this.getImag(); return Math.sqrt(a * a + b * b); }

abs  the problem with the obvious implementation is that it fails in cases where the value of z.abs() can be represented using double but the value of a * a + b * b cannot be represented using double 11

abs 12 1e e-1701e E e200Infinity* 1e200 1e1701e169Infinity* E170 * Double.POSITIVE_INFINITY

13 public double abs() { // avoids intermediate under- and overflow return Math.hypot(this.getReal(), this.getImag()); }

abs  the field that studies solving mathematical problems using computational techniques is called numerical analysis  of interest in computer science, mathematics, engineering, and science  how does Math.hypot work?  for a pure Java implementation the ideas described in the following link work 

add 15 thisother

16 public Complex add(Complex other) { double a = this.getReal(); double b = this.getImag(); double c = other.getReal(); double d = other.getImag(); return new Complex(a + c, b + d); }

multiply 17 thisother

18 public Complex multiply(Complex other) { double a = this.getReal(); double b = this.getImag(); double c = other.getReal(); double d = other.getImag(); return new Complex(a * c - b * d, b * c + a * d); }

Obligatory methods  recall that all classes in Java inherit from java.lang.Object   any class you create inherits all of the public and protected fields and methods of java.lang.Object  the course notes refers to the methods inherited from java.lang.Object as obligatory methods  there are 11 such methods in total, but we are only interested in 3 of them  toString, equals, hashCode 19

toString 20  toString() returns a String representation of the calling object  we can call toString() with our current Complex class even though we have not implemented it  this prints something like on my computer // client of Complex Complex z = new Complex(1, 2); System.out.println(z.toString());

toString 21

public String toString() { StringBuilder b = new StringBuilder(); b.append(this.getReal()); double imag = this.getImag(); if (imag < 0) { b.append(" - "); } else { b.append(" + "); } b.append(Math.abs (imag) ); b.append('i'); return b.toString(); }

Overriding methods  our class is a subclass or child class of java.lang.Object  when a subclass redefines a public or protected method inherited from its superclass, we say that the subclass overrides the inherited method  to override a method, you create a method that has the exact same signature and return type of the method that you want to override  the return type may also be a subtype of the return type of the overridden method (but this is not important for now) 23

Overriding methods  when you override a method you may use the immediately before the method header  if you do so, the compiler will generate an error message if your method does not have the identical signature and return type of a method in a superclass 24

equals() 25  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 // Complex client Complex z = new Complex(1, 2); System.out.println( z.equals(z) ); // true Complex z2 = z; System.out.println( z2.equals(z) ); // true Complex z3 = new Complex(1, 2); System.out.println( z3.equals(z)); // false! [notes 3.2.4]

26 64 client z z2 z3 600Complex object real 1 imag 2 700Complex object real 1 imag z and z2 refer to the object at address 600 z3 refers to the object at address 700 equal states but different objects Complex z = new Complex(1, 2); Complex z2 = z; Complex z3 = new Complex(1, 2);

Object.equals 27  Object.equals checks if two references refer to the same object  x.equals(y) is true if and only if x and y are references to the same object

Complex.equals 28  most value classes should support logical equality  an instance is equal to another instance if their states are equal  e.g. two complex numbers are equal if their real and imaginary parts both have the same values

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

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

EECS1030 Requirements for equals 1. an instance is equal to itself 2. an instance is never equal to null 3. only instances of the exact same type can be equal 4. instances with the same state are equal 31

1. An Instance is Equal to Itself 32  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 ==

public boolean equals(Object obj) { if (this == obj) { return true; }

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

public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; }

3. Instances of the Same Type can be Equal 36  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  you can find the class of an object using Object.getClass() public final Class getClass()  Returns the runtime class of an object.

public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; }

Instances with Same State are Equal 38  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  unfortunately, we cannot yet retrieve the attributes of the parameter obj because it is declared to be an Object in the method signature  we need a cast

public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Complex other = (Complex) obj; }

Instances with Same State are Equal 40  there is a recipe for checking equality of fields 1. if the field 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

public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Complex other = (Complex) obj; if (Double.compare(this.getReal(), other.getReal()) != 0) { return false; } if (Double.compare(this.getImag(), other.getImag()) != 0) { return false; } return true; }

The equals() Contract 42  for reference values equals() is 1. reflexive 2. symmetric 3. transitive 4. consistent 5. must not throw an exception when passed null

The equals() contract: Reflexivity reflexive :  an object is equal to itself  x.equals(x) is true

The equals() contract: Symmetry symmetric :  two objects must agree on whether they are equal  x.equals(y) is true if and only if y.equals(x) is true

The equals() contract: Transitivity 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: Consistency consistent :  repeatedly comparing two objects yields the same result (assuming the state of the objects does not change)

The equals() contract: Non-nullity x.equals(null) is always false and never does not throw an exception

The equals() contract and getClass()  using getClass() makes it relatively easy to ensure that the equals() contract is obeyed  e.g., symmetry and transitivity are easy to ensure  however, using getClass() means that your equals() method won't work as expected in inheritance hierarchies  more on this when we talk about inheritance 48

One more thing regarding equals()  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  we will see how to implement hashCode() in the next lecture or so 49