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.

Slides:



Advertisements
Similar presentations
Classes And Objects II. Recall the LightSwitch Class class LightSwitch { boolean on = true; boolean isOn() { return on; } void switch() { on = !on; }
Advertisements

Chapter 7. Binary Search Trees
Generics, Lists, Interfaces
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Java Programming Abstract classes and Interfaces.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Computer Science 209 Software Development Equality and Comparisons.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
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.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
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.
Gruppe Grøn Effective Java Items: 4, 12, 20, 28 36, 44, 52, 60 1.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
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.
Introduction to Searching and Sorting
CS 106 Introduction to Computer Science I 04 / 28 / 2010 Instructor: Michael Eckmann.
 2006 Pearson Education, Inc. All rights reserved Generics.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
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.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
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.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
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.
CS 106 Introduction to Computer Science I 04 / 20 / 2007 Instructor: Michael Eckmann.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
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[]
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.
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.
1 Interfaces Reading for today: Sec and corresponding ProgramLive material. Also, compare with previous discussions of abstract classes (Sec. 4.7).
Agenda Object Oriented Programming Reading: Chapter 14.
Mixing Static and Non-static
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.
Polymorphism Liskov 8. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
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.
The Java Tutorials Comparable and Comparator. Object Ordering A List may be sorted as follows. Collections.sort(l); If the List consists of String elements,
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
CS2 Module 26 Category: OO Concepts Topic: Interfaces Objectives –Interfaces.
Polymorphism SWE 619. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism Element.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.
1 CSE 331 Comparing objects; Comparable, compareTo, and Comparator slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Searching.
CompareTo.
Information hiding.
The hashCode method.
Non-static classes.
CSE 1030: Implementing Non-Static Features
COMPUTER 2430 Object Oriented Programming and Data Structures I
Implementing Non-Static Features
Searching.
TCSS 143, Autumn 2004 Lecture Notes
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

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 the state of an object  it should set the values of the non-static fields to appropriate values  we should set the fields named real and imag  our complex number class has a single constructor so far 2

3 public class Complex { private double real; private double imag; public Complex(double real, double imag) { this.real = real; this.imag = imag; }

Constructors  our class is missing two constructors commonly found in a value type class  no-argument constructor  a constructor defined as having no parameters  copy constructor  a constructor with a single parameter whose type is the same as the type of the class 4

No-argument constructor 5

6 public class Complex { private double real; private double imag; public Complex(double real, double imag) { this.real = real; this.imag = imag; } public Complex() { this.real = 0; this.imag = 0; }

Copy constructor  a copy constructor copies the state of another object of the same type as the class  it has a single parameter that is the same type as the class  a copy constructor for our complex number class would copy the real and imaginary parts of another complex number 7

8 public Complex(double real, double imag) { this.real = real; this.imag = imag; } public Complex() { this.real = 0; this.imag = 0; } public Complex(Complex other) { this.real = other.getReal(); this.imag = other.getImag(); }

Avoiding Code Duplication  notice that the constructor bodies are almost identical to each other  all three constructors have 2 lines of code  all three constructors set the real and imaginary parts  whenever you see duplicated code you should consider moving the duplicated code into a method  in this case, one of the constructors already does everything we need to implement the other constructors… 9

Constructor chaining  a constructor is allowed to invoke another constructor  when a constructor invokes another constructor it is called constructor chaining  to invoke a constructor in the same class you use the this keyword  if you do this then it must occur on the first line of the constructor body  but you cannot use this in a method to invoke a constructor  we can re-write two of our constructors to use constructor chaining... 10

11 public Complex(double real, double imag) { this.real = real; this.imag = imag; } public Complex() { this(0.0, 0.0); } public Complex(Complex other) { this(other.getReal(), other.getImag()); } invokes

compareTo 12

Comparable Objects 13  many value types have a natural ordering  that is, for two objects x and y, x is less than y is meaningful  Short, Integer, Float, Double, etc  String s can be compared in dictionary order  Date s can be compared in chronological order  you might compare Complex numbers by their absolute value  if your class has a natural ordering, consider implementing the Comparable interface  doing so allows clients to sort arrays or Collection s of your object

Interfaces 14  an interface is (usually) a group of related methods with empty bodies  the Comparable interface has just one method public interface Comparable { int compareTo(T t); }  a class that implements an interfaces promises to provide an implementation for every method in the interface

compareTo() 15  Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.  Throws a ClassCastException if the specified object type cannot be compared to this object.

Complex compareTo 16 public class Complex implements Comparable { // fields, constructors, public int compareTo(Complex other) { double thisAbs = this.abs(); double otherAbs = other.abs(); if (thisAbs > otherAbs) { return 1; } else if (thisAbs < otherAbs) { return -1; } return 0; }

Complex compareTo  don't forget what you learned in EECS1020  you should delegate work to well-tested components where possible  for complex numbers, we need to compare two double values  java.lang.Double has methods that do exactly this 17

Complex compareTo 18 public class Complex implements Comparable { // fields, constructors, public int compareTo(Complex other) { return Double.compare(this.abs(), other.abs()); }

Comparable Contract the sign of the returned int must flip if the order of the two compared objects flip  if x.compareTo(y) > 0 then y.compareTo(x) < 0  if x.compareTo(y) 0  if x.compareTo(y) == 0 then y.compareTo(x) == 0

Comparable Contract compareTo() must be transitive  if x.compareTo(y) > 0 && y.compareTo(z) > 0 then x.compareTo(z) > 0  if x.compareTo(y) < 0 && y.compareTo(z) < 0 then x.compareTo(z) < 0  if x.compareTo(y) == 0 && y.compareTo(z) == 0 then x.compareTo(z) == 0

Comparable Contract if x.compareTo(y) == 0 then the signs of x.compareTo(z) and y.compareTo(z) must be the same

Consistency with equals 22  an implementation of compareTo() is said to be consistent with equals() when if x.compareTo(y) == 0 then x.equals(y) == true  and if x.equals(y) == true then x.compareTo(y) == 0

Not in the Comparable Contract 23  it is not required that compareTo() be consistent with equals()  that is if x.compareTo(y) == 0 then x.equals(y) == false is acceptable  similarly if x.equals(y) == true then x.compareTo(y) != 0 is acceptable  try to come up with examples for both cases above  is Complex compareTo consistent with equals?

Implementing compareTo  if you are comparing fields of type float or double you should use Float.compare or Double.compare instead of, or ==  if your compareTo implementation is broken, then any classes or methods that rely on compareTo will behave erratically  TreeSet, TreeMap  many methods in the utility classes Collections and Arrays 24