Your SlideShare is downloading. ×
0
Object-Oriented Programming Concepts in Java PJ Dillon CS401 Slides adapted from Dr. Ramirez
Intro. to Object-Oriented Programming (OOP) <ul><li>Object-Oriented Programming consists of 3 primary ideas: </li></ul><ul...
Intro. to OOP <ul><ul><li>Inheritance </li></ul></ul><ul><ul><ul><li>Properties of a data type can be passed down to a sub...
Objects and Data Abstraction <ul><li>Consider primitive types </li></ul><ul><ul><li>Each variable represents a single,  si...
Objects and Data Abstraction <ul><li>Consider the  data </li></ul><ul><ul><li>In many applications, data is more complicat...
Objects and Data Abstraction <ul><li>Consider the  operations </li></ul><ul><ul><li>Now consider operations that a Polygon...
Objects and Data Abstraction <ul><ul><li>These operations are actually (logically) PART of the Polygon itself </li></ul></...
Objects and Data Abstraction <ul><ul><li>Objects enable us to  combine the data and operations  of a type together into a ...
Objects and Data Abstraction <ul><ul><li>For multiple objects of the same class, the operations act on the object specifie...
Encapsulation and Data Abstraction <ul><li>Recall that we previously discussed  data abstraction </li></ul><ul><ul><li>We ...
Encapsulation and Data Abstraction <ul><li>As long as we know the method names, params and how to use them, we don’t need ...
Instance Variables <ul><li>Let’s look again at StringBuffer </li></ul><ul><ul><li>Instance Variables </li></ul></ul><ul><u...
Instance Variables <ul><ul><li>Many instance variables are declared with the keyword  private </li></ul></ul><ul><ul><ul><...
Class Methods vs. Instance Methods <ul><ul><li>Recall that methods we discussed before were called  class methods  (or sta...
Class Methods vs. Instance Methods <ul><ul><li>Class methods  have no implicit data to act on </li></ul></ul><ul><ul><ul><...
Constructors, Accessors and Mutators <ul><li>Instance methods can be categorized by what they are designed to do: </li></u...
Constructors, Accessors and Mutators <ul><ul><li>Accessors </li></ul></ul><ul><ul><ul><li>These methods are used to access...
Constructors, Accessors and Mutators <ul><ul><li>Mutators </li></ul></ul><ul><ul><ul><li>Used to change the object in some...
Simple Class Example <ul><li>We can use these ideas to write our own classes </li></ul><ul><ul><li>Let’s look a VERY simpl...
More on Classes and Objects <ul><li>Classes </li></ul><ul><ul><li>Define the nature and properties of objects </li></ul></...
Developing Another Example <ul><li>Remember the things we need for a class: </li></ul><ul><ul><li>Instance variables </li>...
Developing Another Example <ul><ul><li>Once we have the basic structure of the class we can start writing / testing it </l...
Wrappers <ul><li>Much useful Java functionality relies on classes / objects </li></ul><ul><ul><li>Inheritance (Chapter 8) ...
Wrappers <ul><ul><li>Wrapper classes  allow us to get around this problem </li></ul></ul><ul><ul><ul><li>Wrappers are clas...
Wrappers <ul><ul><li>The wrapper classes also provide extra useful functionality for these types </li></ul></ul><ul><ul><u...
Wrappers and Casting <ul><ul><li>However, arithmetic operations are not defined for wrapper classes </li></ul></ul><ul><ul...
Wrappers <ul><ul><li>In Java 1.4 and before: </li></ul></ul><ul><ul><ul><li>Programmer had to do the conversions explicitl...
Intro. to Java Files <ul><li>So far </li></ul><ul><ul><li>Our programs have read input from the keyboard or command line a...
Intro. to Java Files <ul><li>In these situations we need to use  files </li></ul><ul><ul><li>Most files can be classified ...
Text Files <ul><ul><ul><li>Ex: “12345” in a file is simply 5 ASCII characters: </li></ul></ul></ul><ul><ul><ul><ul><li>49 ...
Text Files <ul><ul><li>Advantage of text files: </li></ul></ul><ul><ul><ul><li>Can read them outside of the program by man...
Binary Files <ul><ul><ul><li>Binary Files </li></ul></ul></ul><ul><ul><ul><li>Data in the file is stored in the same way (...
Binary Files <ul><ul><ul><li>Disadvantage: </li></ul></ul></ul><ul><ul><ul><ul><li>Data in the files is not readable excep...
File Streams <ul><li>Recall a  Stream  is a continuous, ordered sequence of bytes coming into or going out of our programs...
Input Files <ul><li>Let's first consider input </li></ul><ul><ul><li>We start with a file and wrap an appropriate input st...
Output Files <ul><li>How about  writing text  to an output file: </li></ul><ul><ul><li>We can't use the Scanner for that, ...
Output Files <ul><ul><ul><li>To increase the writing functionality we can wrap another stream around it – PrintWriter </li...
Text vs. Binary Files <ul><li>We discussed previously that numeric data can often be stored more efficiently in binary for...
Text vs. Binary Files <ul><li>Let’s try this and then compare the sizes of the binary and text files </li></ul><ul><ul><li...
Composition & Inheritance <ul><li>Sometimes we want to build a new class that is largely like one we already have </li></u...
Composition <ul><li>We include an object of the class whose functionality we need as a private instance variable in our ow...
Composition <ul><li>This is ideal when an object of NewClass isn’t logically an object of OldClass </li></ul><ul><ul><li>F...
Inheritance <ul><li>Alternatively, our NewClass can directly “inherit” the properties of OldClass </li></ul><ul><ul><li>Ju...
Inheritance and “is a” <ul><ul><li>We can understand this better by considering the  “is a”  idea </li></ul></ul><ul><ul><...
Inheritance and “is a” <ul><ul><li>Bird, Human and Fish are all Animals </li></ul></ul><ul><ul><li>However, an Animal is n...
Extending Classes <ul><li>Inheritance in Java is implemented by  extend ing a class </li></ul><ul><ul><ul><li>public class...
private, public and protected <ul><ul><li>We already know what public and private declarations mean </li></ul></ul><ul><ul...
Inheritance Example <ul><li>As another example </li></ul><ul><ul><li>Compare MixedNumber class and MixedNumber2 class </li...
Java Class Hierarchy <ul><li>In Java, class  Object  is the base class to all other classes </li></ul><ul><ul><li>If we do...
Polymorphism <ul><li>Idea of polymorphism </li></ul><ul><ul><li>See internet definition: </li></ul></ul><ul><ul><ul><li>On...
Method Overloading <ul><ul><li>This is called  ad hoc polymorphism , or  method overloading </li></ul></ul><ul><ul><ul><li...
Method Overloading <ul><ul><ul><li>If an exact signature match is not possible, the one that is  closest via “widening”  o...
Polymorphism <ul><li>Subclassing Polymorphism </li></ul><ul><ul><li>Sometimes called “true polymorphism” </li></ul></ul><u...
Polymorphism <ul><ul><li>Dynamic (or late) binding </li></ul></ul><ul><ul><ul><li>The code executed for a method call is a...
Polymorphism <ul><li>Ex. Each subclass overrides the move() method in its own way </li></ul><ul><li>Animal [] A = new Anim...
Object, Method and Instance Variable Access <ul><li>When mixing objects of difference classes, some access rules are impor...
Object, Method and Instance Variable Access <ul><ul><li>Ex: </li></ul></ul><ul><ul><ul><li>Suppose class Fish contains a n...
Object, Method and Instance Variable Access <ul><ul><ul><li>Note that we can access these methods or instance variables IN...
Object  Methods <ul><li>We’ve already seen that every class automatically inherits from  Object </li></ul><ul><li>Class Ob...
toString() <ul><li>toString() returns a string representation of the object </li></ul><ul><li>The string “should be a conc...
equals() <ul><li>Indicates whether two objects are logically equal to each other </li></ul><ul><ul><li>Ex.  string1.equals...
Contract of equals() <ul><li>equals() must be: </li></ul><ul><ul><li>Reflexive : for any non-null reference variable, x: <...
Contract of equals() <ul><li>Consider a class SubClass </li></ul><ul><ul><li>Extends SuperClass </li></ul></ul><ul><li>Has...
Contract of equals() <ul><li>Now consider the super class, SuperClass </li></ul><ul><ul><li>Has it’s own equals method </l...
Template for equals() <ul><li>For any class, the general form of the equals() method should be: </li></ul><ul><ul><li>publ...
hashCode() <ul><li>Returns a integer index value for the object </li></ul><ul><ul><li>Used by hashtables to store objects ...
Composition or Inheritance <ul><li>Caveats like those we just discussed arise often with Inheritance </li></ul><ul><li>Als...
Exceptions in Java <ul><li>Run-time errors happen </li></ul><ul><ul><li>User enters incorrect input </li></ul></ul><ul><ul...
Exceptions in Java <ul><li>Exception: </li></ul><ul><ul><li>An occurrence of an erroneous, unusual or unexpected event in ...
Exceptions in Java <ul><ul><li>In newer languages </li></ul></ul><ul><ul><ul><li>Exception handling built into the languag...
Exceptions in Java <ul><li>Java exception handling </li></ul><ul><ul><li>Exceptions are handled using  try-catch  blocks <...
Exceptions in Java <ul><ul><li>If all goes well (no exceptions occur) </li></ul></ul><ul><ul><ul><li>Code in  try  block i...
Exceptions in Java <ul><ul><li>If an exception is  handled </li></ul></ul><ul><ul><ul><li>Execution resumes immediately AF...
Exceptions in Java <ul><li>Checked vs. Unchecked exceptions </li></ul><ul><ul><li>Checked  exceptions </li></ul></ul><ul><...
Exceptions in Java <ul><li>Catching exceptions </li></ul><ul><ul><li>Catching a superclass of an exception will catch subc...
Abstract Classes <ul><li>Abstract classes </li></ul><ul><ul><li>Sometimes in a class hierarchy, a class may be defined sim...
Abstract Classes <ul><ul><li>Subclasses of an abstract class must implement all abstract methods, or they too must be decl...
Interfaces <ul><li>Java allows only  single inheritance </li></ul><ul><ul><li>A new class can be a subclass of only one pa...
Interfaces <ul><ul><li>We may want to identify an object in multiple ways: </li></ul></ul><ul><ul><ul><li>One based on its...
Interfaces <ul><li>A Java  interface  is a named set of methods </li></ul><ul><ul><ul><li>However, no method bodies are gi...
Interfaces <ul><ul><li>Ex: </li></ul></ul><ul><ul><ul><li>public interface Laughable </li></ul></ul></ul><ul><ul><ul><li>{...
Interfaces <ul><li>Ex: </li></ul><ul><ul><ul><li>public class Comedian implements Laughable, Booable </li></ul></ul></ul><...
Interfaces <ul><ul><li>An interface variable can be used to reference any object that implements that interface </li></ul>...
Interfaces <ul><ul><li>Polymorphism and Dynamic Binding also apply to interfaces </li></ul></ul><ul><ul><ul><li>the interf...
&quot;Generic&quot; Operations <ul><ul><li>How does it benefit us to be able to access objects through interfaces? </li></...
“Generic” Operations <ul><ul><li>They all can be compared to each other </li></ul></ul><ul><ul><ul><li>So we need some met...
Simple Sorting <ul><li>What does it mean to  sort  our data? </li></ul><ul><ul><li>Consider an array, A of N items: </li><...
Simple Sorting <ul><li>How do we sort? </li></ul><ul><ul><li>There are MANY ways of sorting data </li></ul></ul><ul><ul><u...
SelectionSort <ul><li>SelectionSort  is very intuitive: </li></ul><ul><ul><li>Idea: </li></ul></ul><ul><ul><ul><li>Find th...
SelectionSort <ul><ul><li>Let’s look at the code </li></ul></ul><ul><ul><ul><li>SortInt.java and ex25.java </li></ul></ul>...
Comparable  Interface <ul><ul><li>Consider the  Comparable  interface: </li></ul></ul><ul><ul><ul><li>It contains one meth...
Using  Comparable <ul><ul><li>Think of the objects we want to sort as “black boxes” </li></ul></ul><ul><ul><ul><li>We know...
Binary Search <ul><li>Consider  Sequential Search  again </li></ul><ul><ul><ul><ul><li>See Procedural Programming slides a...
Binary Search <ul><li>Idea of  Binary Search : </li></ul><ul><ul><li>Searching for a given key, K </li></ul></ul><ul><ul><...
Binary Search <ul><ul><ul><li>What if item is not in array?  We need a stopping condition in the “not found” case  </li></...
Binary Search <ul><ul><li>So is Binary Search really an improvement over Sequential Search </li></ul></ul><ul><ul><ul><li>...
Collections <ul><li>Sorting and Searching are used often </li></ul><ul><li>With Generics, the code only needs written once...
Collections <ul><li>Java refers to these as “Collections” </li></ul><ul><ul><li>Containers of other data objects </li></ul...
List <ul><li>What is a List? </li></ul><ul><ul><li>Let’s consider lists we make in every day life </li></ul></ul><ul><ul><...
List Implementation <ul><li>We now have a concept of a List </li></ul><ul><ul><li>A scheme by which we store and access el...
ArrayList <ul><li>We use an array to store the items in the List </li></ul><ul><ul><li>Arrays have a fixed size </li></ul>...
LinkedList <ul><li>The strict array indexing causes this need for shifting </li></ul><ul><ul><li>Can we avoid this? </li><...
Which and How to Use <ul><li>ArrayList when </li></ul><ul><ul><li>Add and remove mostly from end of list </li></ul></ul><u...
Set <ul><li>Similar to a List except </li></ul><ul><ul><li>No order to the elements </li></ul></ul><ul><ul><li>Cannot cont...
HashSet <ul><li>Imagine implementing a Set with an array </li></ul><ul><ul><li>To maintain the constraint that the Set doe...
Iterators <ul><li>We’ve seen two types of  Collection s so far </li></ul><ul><ul><li>List </li></ul></ul><ul><ul><li>Set <...
Using Iterators <ul><li>Iterator class defines two methods </li></ul><ul><ul><li>hasNext() </li></ul></ul><ul><ul><ul><li>...
Order in Sets <ul><li>The  HashSet  Class is the simplest implementation of the Set interface </li></ul><ul><ul><li>Iterat...
Queue <ul><li>We often don’t need to be able to modify all a Collection’s elements </li></ul><ul><ul><li>Can even be advan...
Stack <ul><li>Consider a stack of plates on a spring in a bin in a cafeteria </li></ul><ul><ul><li>When a plate is added, ...
Stack Implementation <ul><li>How would this best be implemented? </li></ul><ul><ul><li>Array </li></ul></ul><ul><ul><li>Li...
Map <ul><li>The Map Interface differs from a Collection </li></ul><ul><li>Defines a mapping from one set of objects to ano...
Map Implementation <ul><li>Recall our discussion of a Set </li></ul><ul><ul><li>Used  hashCode()  to store object in array...
Iterating over a Map <ul><li>A Map is a complex data structure </li></ul><ul><ul><li>Keys </li></ul></ul><ul><ul><li>Value...
Generics <ul><li>From the previous slides </li></ul><ul><ul><li>Each collection or Iterator returns an Object </li></ul></...
Generics <ul><li>We “parameterize” the instance of our List with the type of object we expect it to contain using the <> s...
Writing a Generic Class <ul><li>Use the <> syntax in the class defintion </li></ul><ul><li>public interface List<E> </li><...
Subtyping with Generics <ul><li>Consider the following code: </li></ul><ul><li>List<String> listS = new ArrayList<String>(...
Wildcards in Generics <ul><li>Ex: In ex28, we had the method: </li></ul><ul><li>public void printCollection(Collection c) ...
Wildcards in Generics <ul><li>Ex: </li></ul><ul><li>public void printCollection(Collection<?> c){ </li></ul><ul><li>for(Ob...
Bounded Wildcards <ul><li>Recall our Animal, Fish, Bird, Person classes </li></ul><ul><li>We’d like to write a method like...
Bounded Wildcards <ul><li>The solution is a bounded wildcard: </li></ul><ul><li>printAnimals(Collection<? extends Animal> ...
Bounded Wildcards <ul><li>The ‘ ? extends MyClass ’ syntax defines an upper bound </li></ul><ul><li>Likewise, ‘ ? super My...
Generic Methods <ul><li>Suppose we want to write a method copies an array into a Collection: </li></ul><ul><li>public void...
Upcoming SlideShare
Loading in...5
×

OOP Principles

928

Published on

Object Oriented Programing concepts useful beginner.............

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
928
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
53
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Consider P.translate(3,3) vs. P2.translate(3,3) In both cases we are moving a Polygon 3 over and 3 down – the difference is which Polygon is being moved
  • Demonstrate propagation on board
  • We can’t write a method that can sort “anything”, but we can write a method that can sort any Comparable objects – note the use of the interface here
  • See text for finding minimum value of an array. Note that sorting here is simply finding the minimum value and then swapping over and over – but considering a smaller array each time
  • Grocery List, Movie List, Buddy List, To-Do List, Team Roster, Course Roster, Venue List, Guest List, Group List
  • Transcript of "OOP Principles"

    1. 1. Object-Oriented Programming Concepts in Java PJ Dillon CS401 Slides adapted from Dr. Ramirez
    2. 2. Intro. to Object-Oriented Programming (OOP) <ul><li>Object-Oriented Programming consists of 3 primary ideas: </li></ul><ul><ul><li>Data Abstraction and Encapsulation </li></ul></ul><ul><ul><ul><li>Operations on the data are considered to be part of the data type </li></ul></ul></ul><ul><ul><ul><li>We can understand and use a data type without knowing all of its implementation details </li></ul></ul></ul><ul><ul><ul><ul><li>Neither how the data is represented nor how the operations are implemented </li></ul></ul></ul></ul><ul><ul><ul><ul><li>We just need to know the interface (or method headers) – how to “communicate” with the object </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Compare to functional abstraction with methods </li></ul></ul></ul></ul><ul><ul><ul><li>We discussed this somewhat already and will do so more in Chapter 4 </li></ul></ul></ul>
    3. 3. Intro. to OOP <ul><ul><li>Inheritance </li></ul></ul><ul><ul><ul><li>Properties of a data type can be passed down to a sub-type – we can build new types from old ones </li></ul></ul></ul><ul><ul><ul><li>We can build class hierarchies with many levels of inheritance </li></ul></ul></ul><ul><ul><ul><li>We will discuss this more in Chapter 8 </li></ul></ul></ul><ul><ul><li>Polymorphism </li></ul></ul><ul><ul><ul><li>Operations used with a variable are based on the class of the object being accessed, not the class of the variable </li></ul></ul></ul><ul><ul><ul><li>Parent type and sub-type objects can be accessed in a consistent way </li></ul></ul></ul><ul><ul><ul><li>We will discuss this more in Chapter 9 </li></ul></ul></ul>
    4. 4. Objects and Data Abstraction <ul><li>Consider primitive types </li></ul><ul><ul><li>Each variable represents a single, simple data value </li></ul></ul><ul><ul><li>Any operations that we perform on the data are external to that data </li></ul></ul><ul><ul><li>X + Y </li></ul></ul>X 10 Y 5 +
    5. 5. Objects and Data Abstraction <ul><li>Consider the data </li></ul><ul><ul><li>In many applications, data is more complicated than just a simple value </li></ul></ul><ul><ul><li>Ex: A Polygon – a sequence of connected points </li></ul></ul><ul><ul><ul><li>The data here are actually: </li></ul></ul></ul><ul><ul><ul><ul><li>int [] xpoints – an array of x-coordinates </li></ul></ul></ul></ul><ul><ul><ul><ul><li>int [] ypoints – an array of y-coordinates </li></ul></ul></ul></ul><ul><ul><ul><ul><li>int npoints – the number of points actually in the Polygon </li></ul></ul></ul></ul><ul><ul><ul><li>Note that individually the data are just ints </li></ul></ul></ul><ul><ul><ul><ul><li>However, together they make up a Polygon </li></ul></ul></ul></ul><ul><ul><ul><li>This is fundamental to object-oriented programming (OOP) </li></ul></ul></ul>
    6. 6. Objects and Data Abstraction <ul><li>Consider the operations </li></ul><ul><ul><li>Now consider operations that a Polygon can do </li></ul></ul><ul><ul><ul><li>Note how that is stated – we are seeing what a Polygon CAN DO rather than WHAT CAN BE DONE to it </li></ul></ul></ul><ul><ul><ul><li>This is another fundamental idea of OOP – objects are ACTIVE rather than PASSIVE </li></ul></ul></ul><ul><ul><ul><li>Ex: </li></ul></ul></ul><ul><ul><ul><ul><li>void addPoint(int x, int y) – add a new point to Polygon </li></ul></ul></ul></ul><ul><ul><ul><ul><li>boolean contains(double x, double y) – is point (x,y) within the boundaries of the Polygon </li></ul></ul></ul></ul><ul><ul><ul><ul><li>void translate(int deltaX, int deltaY) – move all points in the Polygon by deltaX and deltaY </li></ul></ul></ul></ul>
    7. 7. Objects and Data Abstraction <ul><ul><li>These operations are actually (logically) PART of the Polygon itself </li></ul></ul><ul><ul><li>int [] theXs = {0, 4, 4}; int [] theYs = {0, 0, 2}; int num = 2; Polygon P = new Polygon(theXs, theYs, num); P.addPoint(0, 2); if ( P.contains(2, 1) ) System.out.println(“Inside P”); else System.out.println(“Outside P”); P.translate(2, 3); </li></ul></ul><ul><ul><ul><li>We are not passing the Polygon as an argument, we are calling the methods FROM the Polygon </li></ul></ul></ul>
    8. 8. Objects and Data Abstraction <ul><ul><li>Objects enable us to combine the data and operations of a type together into a single entity </li></ul></ul>P xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate() Thus, the operations are always implicitly acting on the object’s data Ex: translate means translate the points that make up P
    9. 9. Objects and Data Abstraction <ul><ul><li>For multiple objects of the same class, the operations act on the object specified </li></ul></ul><ul><ul><li>int [] moreXs = {8, 11, 8}; int [] moreYs = {0, 2, 4}; Polygon P2 = new Polygon(moreXs, moreYs, 3); </li></ul></ul>P xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate() P2 xpoints [8,11,8]] ypoints [0,2,4] npoints 3 addPoint() contains() translate()
    10. 10. Encapsulation and Data Abstraction <ul><li>Recall that we previously discussed data abstraction </li></ul><ul><ul><li>We do not need to know the implementation details of a data type in order to use it </li></ul></ul><ul><ul><ul><li>This includes the methods AND the actual data representation of the object </li></ul></ul></ul><ul><ul><li>This concept is exemplified through objects </li></ul></ul><ul><ul><ul><li>We can think of an object as a container with data and operations inside </li></ul></ul></ul><ul><ul><ul><ul><li>We can see some of the data and some of the operations, but others are kept hidden from us </li></ul></ul></ul></ul><ul><ul><ul><ul><li>The ones we can see give us the functionality of the objects </li></ul></ul></ul></ul>
    11. 11. Encapsulation and Data Abstraction <ul><li>As long as we know the method names, params and how to use them, we don’t need to know how the actual data is stored </li></ul><ul><ul><li>Note that I can use a Polygon without knowing how the data is stored OR how the methods are implemented </li></ul></ul><ul><ul><ul><li>I know it has points but I don’t know how they are stored </li></ul></ul></ul><ul><ul><ul><li>Data Abstraction! </li></ul></ul></ul>P xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate()
    12. 12. Instance Variables <ul><li>Let’s look again at StringBuffer </li></ul><ul><ul><li>Instance Variables </li></ul></ul><ul><ul><ul><li>These are the data values within an object </li></ul></ul></ul><ul><ul><ul><ul><li>Used to store the object’s information </li></ul></ul></ul></ul><ul><ul><ul><li>As we said previously, when using data abstraction we don’t need to know explicitly what these are in order to use a class </li></ul></ul></ul><ul><ul><ul><li>For example, look at the API for StringBuffer </li></ul></ul></ul><ul><ul><ul><ul><li>Note that the instance variables are not even shown there </li></ul></ul></ul></ul><ul><ul><ul><li>In actuality it is a variable-length array with a counter to keep track of how many locations are being used and is actually inherited from AbstractStringBuilder </li></ul></ul></ul><ul><ul><ul><ul><li>See source in StringBuffer.java and AbstractStringBuilder.java – cool!!! </li></ul></ul></ul></ul>
    13. 13. Instance Variables <ul><ul><li>Many instance variables are declared with the keyword private </li></ul></ul><ul><ul><ul><li>This means that they cannot be directly accessed outside the class itself </li></ul></ul></ul><ul><ul><ul><li>Instance variables are typically declared to be private, based on the data abstraction that we discussed earlier </li></ul></ul></ul><ul><ul><ul><ul><li>Recall that we do not need to know how the data is represented in order to use the type </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Therefore why even allow us to see it? </li></ul></ul></ul></ul><ul><ul><ul><li>In AbstractStringBuilder the value variable has no keyword modifier </li></ul></ul></ul><ul><ul><ul><ul><li>This makes it private to the package </li></ul></ul></ul></ul>
    14. 14. Class Methods vs. Instance Methods <ul><ul><li>Recall that methods we discussed before were called class methods (or static methods) </li></ul></ul><ul><ul><ul><li>These were not associated with any object </li></ul></ul></ul><ul><ul><li>Now, however we WILL associate methods with objects (as shown with Polygon) </li></ul></ul><ul><ul><li>These methods are called instance methods because they are associated with individual instances (or objects) of a class </li></ul></ul><ul><ul><ul><li>StringBuffer B = new StringBuffer(“this is “); </li></ul></ul></ul><ul><ul><ul><li>B. append (“really fun stuff!”); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(B. toString ()); </li></ul></ul></ul>
    15. 15. Class Methods vs. Instance Methods <ul><ul><li>Class methods have no implicit data to act on </li></ul></ul><ul><ul><ul><li>All data must be passed into them using arguments </li></ul></ul></ul><ul><ul><li>Class methods are called using: </li></ul></ul><ul><ul><ul><li>ClassName .methodName(param list) </li></ul></ul></ul><ul><ul><li>Instance methods have implicit data associated with an Object </li></ul></ul><ul><ul><ul><li>Other data can be passed as arguments, but there is always an underlying object to act upon </li></ul></ul></ul><ul><ul><li>Instance methods are called using: </li></ul></ul><ul><ul><ul><li>VariableName .methodName(param list) </li></ul></ul></ul>
    16. 16. Constructors, Accessors and Mutators <ul><li>Instance methods can be categorized by what they are designed to do: </li></ul><ul><ul><li>Constructors </li></ul></ul><ul><ul><ul><li>These are special instance methods that are called when an object is first created </li></ul></ul></ul><ul><ul><ul><li>They are the only methods that do not have a return value (not even void) </li></ul></ul></ul><ul><ul><ul><li>They are typically used to initialize the instance variables of an object </li></ul></ul></ul><ul><ul><ul><li>StringBuffer B = new StringBuffer(“hello there”); </li></ul></ul></ul><ul><ul><ul><li>B = new StringBuffer(); // default constructor </li></ul></ul></ul><ul><ul><ul><li>B = new StringBuffer(10); // capacity 10 </li></ul></ul></ul>
    17. 17. Constructors, Accessors and Mutators <ul><ul><li>Accessors </li></ul></ul><ul><ul><ul><li>These methods are used to access the object in some way without changing it </li></ul></ul></ul><ul><ul><ul><li>Usually used to get information from it </li></ul></ul></ul><ul><ul><ul><li>No special syntax – categorized simply by their effect </li></ul></ul></ul><ul><ul><ul><ul><li>StringBuffer B = new StringBuffer(“hello there”); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>char c = B. charAt (4); // c == ‘o’ </li></ul></ul></ul></ul><ul><ul><ul><ul><li>String S = B. substring (3, 9); // S == “lo the” </li></ul></ul></ul></ul><ul><ul><ul><ul><li> // note that end index is NOT inclusive </li></ul></ul></ul></ul><ul><ul><ul><ul><li>int n = B. length (); // n == 11 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>These methods give us information about the StringBuffer without revealing the implementation details </li></ul></ul></ul></ul>
    18. 18. Constructors, Accessors and Mutators <ul><ul><li>Mutators </li></ul></ul><ul><ul><ul><li>Used to change the object in some way </li></ul></ul></ul><ul><ul><ul><li>Since the instance variables are usually private, we use mutators to change the object in a specified way without needing to know the instance variables </li></ul></ul></ul><ul><ul><ul><ul><li>B. setCharAt (0, ‘j’); // B == “jello there” </li></ul></ul></ul></ul><ul><ul><ul><ul><li>B. delete (5,6); // B == “jello here” </li></ul></ul></ul></ul><ul><ul><ul><ul><li>B. insert (6, “is “); // B == “jello is here”; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>These methods change the contents or properties of the StringBuffer object </li></ul></ul></ul></ul><ul><ul><li>We use accessors and mutators to indirectly access the data, since we don’t have direct access – see ex12.java </li></ul></ul>
    19. 19. Simple Class Example <ul><li>We can use these ideas to write our own classes </li></ul><ul><ul><li>Let’s look a VERY simple example: </li></ul></ul><ul><ul><ul><li>A circle constricted to an integer radius </li></ul></ul></ul><ul><ul><ul><li>IntCircle </li></ul></ul></ul><ul><ul><ul><ul><li>Instance variable : private int radius </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Cannot directly access it from outside the class </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>Constructor : take an int argument and initialize a new circle with the given radius </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Accessors : </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>public double area(); </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>public double circumference(); </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>public String toString(); </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>Mutator : </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>public void setRadius(int newRadius); </li></ul></ul></ul></ul></ul><ul><ul><ul><li>See IntCircle.java and ex13.java (note COMMENTS!!!) </li></ul></ul></ul>
    20. 20. More on Classes and Objects <ul><li>Classes </li></ul><ul><ul><li>Define the nature and properties of objects </li></ul></ul><ul><li>Objects </li></ul><ul><ul><li>Instances of classes </li></ul></ul><ul><li>Let’s learn more about these by developing another example together </li></ul><ul><li>Goal: </li></ul><ul><ul><li>Write one or more classes that represent a CD (compact disc) </li></ul></ul><ul><ul><li>Write a simple driver program to test it </li></ul></ul>
    21. 21. Developing Another Example <ul><li>Remember the things we need for a class: </li></ul><ul><ul><li>Instance variables </li></ul></ul><ul><ul><li>Constructors </li></ul></ul><ul><ul><li>Accessors </li></ul></ul><ul><ul><li>Mutators </li></ul></ul>
    22. 22. Developing Another Example <ul><ul><li>Once we have the basic structure of the class we can start writing / testing it </li></ul></ul><ul><ul><li>A good approach is to do it in a modular, step-by-step way </li></ul></ul><ul><ul><ul><li>Ex: Determine some instance variables, a constructor or two and an accessor to “output” the data in the class </li></ul></ul></ul><ul><ul><ul><li>Write a simple driver program to test these features </li></ul></ul></ul><ul><ul><ul><ul><li>Once a method has been written and tested we don’t have to worry about it anymore! </li></ul></ul></ul></ul><ul><ul><ul><li>Add more to the class, testing it with additional statements in the driver program </li></ul></ul></ul><ul><ul><li>Let’s do this now! </li></ul></ul>
    23. 23. Wrappers <ul><li>Much useful Java functionality relies on classes / objects </li></ul><ul><ul><li>Inheritance (Chapter 8) </li></ul></ul><ul><ul><li>Polymorphic access (Chapter 9) </li></ul></ul><ul><ul><li>Interfaces (Chapter 6) </li></ul></ul><ul><li>Unfortunately, the Java primitive types are NOT classes, and thus cannot be used in this way </li></ul><ul><ul><li>If I make an array of Object or any other class, primitive types cannot be stored in it </li></ul></ul>
    24. 24. Wrappers <ul><ul><li>Wrapper classes allow us to get around this problem </li></ul></ul><ul><ul><ul><li>Wrappers are classes that “wrap” objects around primitive values, thus making them compatible with other Java classes </li></ul></ul></ul><ul><ul><ul><ul><li>We can't store an int in an array of Object, but we could store an Integer </li></ul></ul></ul></ul><ul><ul><ul><li>Each Java primitive type has a corresponding wrapper </li></ul></ul></ul><ul><ul><ul><ul><li>Ex: Integer, Float, Double, Boolean </li></ul></ul></ul></ul><ul><ul><ul><li>Ex: Integer i, j, k; </li></ul></ul></ul><ul><ul><ul><ul><li>i = new Integer(20); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>j = new Integer(40); </li></ul></ul></ul></ul>
    25. 25. Wrappers <ul><ul><li>The wrapper classes also provide extra useful functionality for these types </li></ul></ul><ul><ul><ul><li>Ex: Integer.parseInt() is a static method that enables us to convert from a String into an int </li></ul></ul></ul><ul><ul><ul><li>Ex: Character.isLetter() is a static method that tests if a letter is a character or not </li></ul></ul></ul><ul><ul><li>See more in API </li></ul></ul>int Integer double Double
    26. 26. Wrappers and Casting <ul><ul><li>However, arithmetic operations are not defined for wrapper classes </li></ul></ul><ul><ul><ul><li>So if we want to do any “math” with our wrappers, we need to get the underlying primitive values </li></ul></ul></ul><ul><ul><ul><li>If we want to keep the wrapper, we then have to wrap the result back up </li></ul></ul></ul><ul><ul><ul><li>Logically, to do the following: </li></ul></ul></ul><ul><ul><ul><li>k = i + j; </li></ul></ul></ul><ul><ul><ul><li>The actual computation being done is </li></ul></ul></ul><ul><ul><ul><li>k = new Integer(i.intValue() + j.intValue()); </li></ul></ul></ul><ul><ul><ul><ul><li>In words: Get the primitive value of each Integer object, add them, then create a new Integer object with the result </li></ul></ul></ul></ul>
    27. 27. Wrappers <ul><ul><li>In Java 1.4 and before: </li></ul></ul><ul><ul><ul><li>Programmer had to do the conversions explicitly </li></ul></ul></ul><ul><ul><ul><ul><li>Painful! </li></ul></ul></ul></ul><ul><ul><li>In Java 1.5 autoboxing was added </li></ul></ul><ul><ul><ul><li>This does the conversion back and forth automatically </li></ul></ul></ul><ul><ul><ul><li>Saves the programmer some keystrokes </li></ul></ul></ul><ul><ul><ul><li>However, the work STILL IS DONE, so from an efficiency point of view we are not saving </li></ul></ul></ul><ul><ul><ul><li>Should not use unless absolutely needed </li></ul></ul></ul><ul><ul><li>We will see more on how wrappers are useful after we discuss inheritance, polymorphism and interfaces </li></ul></ul>
    28. 28. Intro. to Java Files <ul><li>So far </li></ul><ul><ul><li>Our programs have read input from the keyboard or command line arguments and written output to the monitor </li></ul></ul><ul><li>This works fine in some situations, but is not so good in others: </li></ul><ul><ul><li>What if we have a large amount of output that we need to save? </li></ul></ul><ul><ul><li>What if we need to initialize a database that is used in our program? </li></ul></ul><ul><ul><li>What if output from one program must be input to another? </li></ul></ul>
    29. 29. Intro. to Java Files <ul><li>In these situations we need to use files </li></ul><ul><ul><li>Most files can be classified into two groups: </li></ul></ul><ul><ul><ul><li>Text Files </li></ul></ul></ul><ul><ul><ul><li>Data is a sequence of ASCII characters stored sequentially </li></ul></ul></ul><ul><ul><ul><li>Any “larger” data types are still stored as characters and must be “built” when they are read in </li></ul></ul></ul><ul><ul><ul><ul><li>Ex: Strings are sequences of characters </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Ex: ints are also sequences of characters, but interpreted in a different way </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>To create an actual int we need to convert the characters – this is what the parseInt method in the Integer class does </li></ul></ul></ul></ul></ul>
    30. 30. Text Files <ul><ul><ul><li>Ex: “12345” in a file is simply 5 ASCII characters: </li></ul></ul></ul><ul><ul><ul><ul><li>49 50 51 52 53 </li></ul></ul></ul></ul><ul><ul><ul><li>To convert it into an actual int requires processing the characters: </li></ul></ul></ul><ul><ul><ul><ul><li>We know ‘0’ is ASCII 48 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>So our integer is </li></ul></ul></ul></ul><ul><ul><ul><ul><li>(49-48)x10 4 + (50-48)x10 3 + (51-48)x10 2 + (52-48)x10 1 + (53-48)x10 0 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>This can be done in a nice efficient way using a simple loop, and is what the parseInt method does </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Let’s do it ourselves to see how it can be done </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Any suggestions on how to start? </li></ul></ul></ul></ul><ul><ul><ul><li>See MyInteger.java and ex14.java </li></ul></ul></ul>
    31. 31. Text Files <ul><ul><li>Advantage of text files: </li></ul></ul><ul><ul><ul><li>Can read them outside of the program by many different editors or programs </li></ul></ul></ul><ul><ul><ul><li>Easy to create </li></ul></ul></ul><ul><ul><li>Disadvantage of text files: </li></ul></ul><ul><ul><ul><li>Must be converted into the desired types as they are read in (as demonstrated with parseInt) </li></ul></ul></ul><ul><ul><ul><ul><li>This takes time to do and slows I/O </li></ul></ul></ul></ul><ul><ul><ul><li>Not the most efficient way to store non-String data </li></ul></ul></ul><ul><ul><ul><ul><li>Ex: int 12345678 requires 8 bytes in a text file, but only needs 4 bytes in the computer as an int or in a binary file </li></ul></ul></ul></ul>
    32. 32. Binary Files <ul><ul><ul><li>Binary Files </li></ul></ul></ul><ul><ul><ul><li>Data in the file is stored in the same way (or in a “serialized” version) that it is stored in the program </li></ul></ul></ul><ul><ul><ul><li>We can store arbitrary bytes or we can store “whole” data types, including primitive types (int, double, etc.) and objects (String, any other Serializable object type) </li></ul></ul></ul><ul><ul><ul><ul><li>We will discuss Serializable more later </li></ul></ul></ul></ul><ul><ul><ul><li>Advantages: </li></ul></ul></ul><ul><ul><ul><ul><li>Since data is already in its binary form, reading and writing require little if any conversion and is faster than for text files </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Non-string data can often be stored more efficiently in its binary form than in ASCII form </li></ul></ul></ul></ul>
    33. 33. Binary Files <ul><ul><ul><li>Disadvantage: </li></ul></ul></ul><ul><ul><ul><ul><li>Data in the files is not readable except via a specific computer program </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Ex: A Java object in a file can only be read in by a Java program </li></ul></ul></ul></ul></ul><ul><ul><li>There are reasons to use both of these types of files in various applications </li></ul></ul>
    34. 34. File Streams <ul><li>Recall a Stream is a continuous, ordered sequence of bytes coming into or going out of our programs </li></ul><ul><li>We can create streams to read from or write to files </li></ul><ul><li>In Java, file access is provided through a hierarchy of file and stream classes </li></ul><ul><ul><li>These allow various different access functionalities implemented in a systematic, consistent way </li></ul></ul><ul><ul><li>Often we “wrap” streams around others to provide more specific access </li></ul></ul><ul><ul><ul><li>Stream wrappers are a similar notion to our primitive type wrappers – in both cases we are wrapping an object around other data to increase the functionality of the data </li></ul></ul></ul><ul><ul><ul><ul><li>However, in this case the data being “wrapped” is already an object </li></ul></ul></ul></ul>
    35. 35. Input Files <ul><li>Let's first consider input </li></ul><ul><ul><li>We start with a file and wrap an appropriate input stream object around it </li></ul></ul><ul><ul><li>We want to use one or more input streams </li></ul></ul><ul><ul><li>Alternatively, we could wrap a Scanner around a file to read it in as tokens, as we did for standard input </li></ul></ul><ul><li>Let's look at ex15.java </li></ul>
    36. 36. Output Files <ul><li>How about writing text to an output file: </li></ul><ul><ul><li>We can't use the Scanner for that, so we need to look at some other classes </li></ul></ul><ul><ul><ul><li>First we create a File object: </li></ul></ul></ul><ul><ul><ul><ul><li>File theFile = new File(&quot;ex12out.txt&quot;); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>This will not necessarily create a file – it simply associates a logical file with the file name provided </li></ul></ul></ul></ul><ul><ul><ul><li>Next we wrap a FileOutputStream around it </li></ul></ul></ul><ul><ul><ul><ul><li>FileOutputStream fo; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>fo = new FileOutputStream(theFile); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>The above will start writing at the beginning of the file – we could also open it for append </li></ul></ul></ul></ul><ul><ul><ul><ul><li>fo = new FileOutputStream(theFile, true); </li></ul></ul></ul></ul><ul><ul><ul><li>At this point we could write to our file </li></ul></ul></ul><ul><ul><ul><ul><li>However, FileOutputStream only allows a few primitive writing operations (see API) </li></ul></ul></ul></ul>
    37. 37. Output Files <ul><ul><ul><li>To increase the writing functionality we can wrap another stream around it – PrintWriter </li></ul></ul></ul><ul><ul><ul><ul><li>PrintWriter outFile = new PrintWriter(fo); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>This allows us to use print and println for our primitive types and object types </li></ul></ul></ul></ul><ul><ul><ul><li>We don’t actually need all of the intermediate variables in all cases: </li></ul></ul></ul><ul><ul><ul><ul><li>PrintWriter p = new PrintWriter(new </li></ul></ul></ul></ul><ul><ul><ul><ul><li> FileOutputStream(new </li></ul></ul></ul></ul><ul><ul><ul><ul><li> File(&quot;ex12out.txt&quot;))); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Note that we are still creating 3 objects, but we are wrapping the inner two right away, thereby avoiding the extra variables </li></ul></ul></ul></ul><ul><ul><ul><li>See ex16.java </li></ul></ul></ul>
    38. 38. Text vs. Binary Files <ul><li>We discussed previously that numeric data can often be stored more efficiently in binary form than in text form </li></ul><ul><li>Let's compare the two by writing the same data (numbers) to a text file and a binary file </li></ul><ul><li>Since the data is just numbers we can use a DataOutputStream for our output </li></ul><ul><ul><li>Allows only simple methods such as writeInt(), writeDouble(), etc </li></ul></ul>
    39. 39. Text vs. Binary Files <ul><li>Let’s try this and then compare the sizes of the binary and text files </li></ul><ul><ul><li>We will generate a number of random ints and random doubles </li></ul></ul><ul><ul><li>Store each in a text file and in a binary file and compare sizes at the end </li></ul></ul><ul><ul><ul><li>Note that the size of the integer text file depends greatly on the values of the integers, while the size of the integer binary file is independent of the values </li></ul></ul></ul><ul><ul><ul><ul><li>If we are storing very small integers, using a text file will actually save us space, but for large integers it will cost us space </li></ul></ul></ul></ul><ul><ul><li>ex17.java </li></ul></ul>
    40. 40. Composition & Inheritance <ul><li>Sometimes we want to build a new class that is largely like one we already have </li></ul><ul><ul><li>Much of the functionality we need is already there, but some things need to be added or changed </li></ul></ul><ul><li>We can achieve this in object-oriented languages using one of two ways </li></ul><ul><ul><li>Composition </li></ul></ul><ul><ul><li>Inheritance </li></ul></ul>
    41. 41. Composition <ul><li>We include an object of the class whose functionality we need as a private instance variable in our own class </li></ul><ul><li>public class NewClass </li></ul><ul><li>{ </li></ul><ul><li>private OldClass oldVar; </li></ul><ul><li>… </li></ul><ul><ul><li>Referred to as a “has a” relationship </li></ul></ul><ul><ul><li>NewClass “has an” OldClass instance </li></ul></ul><ul><li>We then write methods that wrap around similar methods of included class </li></ul><ul><li>public int foo(int arg) </li></ul><ul><li>{ </li></ul><ul><li>return oldVar.foo(arg); </li></ul><ul><li>} </li></ul><ul><li>The new class then seems to provide the same functionality as the included class </li></ul><ul><li>In addition to any new functionality </li></ul>
    42. 42. Composition <ul><li>This is ideal when an object of NewClass isn’t logically an object of OldClass </li></ul><ul><ul><li>Fails the “is a” test </li></ul></ul><ul><li>This is scheme is used by the input and output stream classes of the java.io package </li></ul><ul><ul><li>Ex: </li></ul></ul><ul><ul><ul><li>DataOutputStream out = new DataOutputStream(new FileOutputStream(“file.out”)); </li></ul></ul></ul><ul><ul><li>‘ out’ stores the passed in FileOutputStream as an instance variable </li></ul></ul><ul><ul><li>A FileOutputStream isn’t necessarily a DataOutputStream, nor is a DataOutputStream necessarily a FileOutputStream </li></ul></ul><ul><ul><li>Both are still output stream objects, though </li></ul></ul>
    43. 43. Inheritance <ul><li>Alternatively, our NewClass can directly “inherit” the properties of OldClass </li></ul><ul><ul><li>Just then need to add the new properties </li></ul></ul><ul><li>Eliminates the need to redefine identical functionality in NewClass </li></ul><ul><ul><li>The OldClass public interface can be access directly by the user </li></ul></ul><ul><li>Can still augment the inherited interface </li></ul><ul><li>Semantically defines a logical relationship between the two objects </li></ul>
    44. 44. Inheritance and “is a” <ul><ul><li>We can understand this better by considering the “is a” idea </li></ul></ul><ul><ul><ul><li>A subclass object “is a” superclass object </li></ul></ul></ul><ul><ul><ul><li>However, some extra instance variables and methods may have been added and some other methods may have been changed </li></ul></ul></ul><ul><ul><li>Note that “is a” is a one way operation </li></ul></ul><ul><ul><ul><li>Subclass “is a” superclass (specific &quot;is a&quot; general) </li></ul></ul></ul><ul><ul><ul><ul><li>With modifications / additions </li></ul></ul></ul></ul><ul><ul><ul><li>Superclass is NOT a subclass (general not &quot;is a&quot; specific </li></ul></ul></ul><ul><ul><ul><ul><li>Missing some properties </li></ul></ul></ul></ul><ul><ul><li>Ex: Bird “is a” Animal </li></ul></ul>
    45. 45. Inheritance and “is a” <ul><ul><li>Bird, Human and Fish are all Animals </li></ul></ul><ul><ul><li>However, an Animal is not necessarily a Bird, Human or Fish </li></ul></ul>Animal Bird Human Fish is a is a is a
    46. 46. Extending Classes <ul><li>Inheritance in Java is implemented by extend ing a class </li></ul><ul><ul><ul><li>public class NewClass extends OldClass </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>… </li></ul></ul></ul><ul><ul><li>We then continue the definition of NewClass as normal </li></ul></ul><ul><ul><li>However, implicit in NewClass are all data and operations associated with OldClass </li></ul></ul><ul><ul><ul><li>Even though we don’t see them in the definition </li></ul></ul></ul>
    47. 47. private, public and protected <ul><ul><li>We already know what public and private declarations mean </li></ul></ul><ul><ul><li>The protected declaration is between public and private </li></ul></ul><ul><ul><ul><li>Protected data and methods are directly accessible in the base class and in any subclasses and in the current package </li></ul></ul></ul><ul><ul><ul><li>However, they are not directly accessible anywhere else </li></ul></ul></ul><ul><ul><li>Note that private declarations are STILL PART of subclasses, but they are not directly accessible from the subclass’ point of view </li></ul></ul><ul><ul><ul><li>See SuperClass.java, SubClass.java and ex18.java </li></ul></ul></ul>
    48. 48. Inheritance Example <ul><li>As another example </li></ul><ul><ul><li>Compare MixedNumber class and MixedNumber2 class </li></ul></ul><ul><ul><li>Both utilize the authors' RationalNumber class to do most of the &quot;work&quot; </li></ul></ul><ul><ul><li>Both also have the same functionality, but MixedNumber uses composition and MixedNumber2 uses inheritance </li></ul></ul><ul><ul><ul><li>Note simplicity of MixedNumber2 methods </li></ul></ul></ul><ul><ul><ul><li>Read over the comments carefully! </li></ul></ul></ul><ul><ul><ul><li>See RationalNumber.java, MixedNumber.java and MixedNumber2.java </li></ul></ul></ul>
    49. 49. Java Class Hierarchy <ul><li>In Java, class Object is the base class to all other classes </li></ul><ul><ul><li>If we do not explicitly say extends in a new class definition, it implicitly extends Object </li></ul></ul><ul><ul><li>The tree of classes that extend from Object and all of its subclasses are is called the class hierarchy </li></ul></ul><ul><ul><li>All classes eventually lead back up to Object </li></ul></ul><ul><ul><li>This will enable consistent access of objects of different classes, as we shall see shortly </li></ul></ul>
    50. 50. Polymorphism <ul><li>Idea of polymorphism </li></ul><ul><ul><li>See internet definition: </li></ul></ul><ul><ul><ul><li>On Google type “definition polymorphism” and see the results </li></ul></ul></ul><ul><ul><ul><ul><li>This search works for many CS terms that you may be curious about </li></ul></ul></ul></ul><ul><ul><ul><li>http://www.wordiq.com/definition/Polymorphism_%28computer_science%29 </li></ul></ul></ul><ul><ul><li>Generally, it allows us to mix methods and objects of different types in a consistent way </li></ul></ul>
    51. 51. Method Overloading <ul><ul><li>This is called ad hoc polymorphism , or method overloading </li></ul></ul><ul><ul><ul><li>In this case different methods within the same class or in a common hierarchy share the same name but have different method signatures (name + parameters) </li></ul></ul></ul><ul><ul><ul><ul><li>public static float max(float a, float b) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>public static float max(float a, float b, float c) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>public static int max(int a, int b) </li></ul></ul></ul></ul><ul><ul><ul><li>When a method is called, the call signature is matched to the correct method version </li></ul></ul></ul><ul><ul><ul><ul><li>Note: This is done during program COMPILATION </li></ul></ul></ul></ul>
    52. 52. Method Overloading <ul><ul><ul><li>If an exact signature match is not possible, the one that is closest via “widening” of the values is used </li></ul></ul></ul><ul><ul><ul><ul><li>“ Widening” means that values of “smaller” types are cast into values of “larger” types </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Ex: int to long int to float float to double </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>Fewer widenings provides a &quot;closer&quot; match </li></ul></ul></ul></ul><ul><ul><ul><li>If two or more versions of the method are possible with the same amount of “widening”, the call is ambiguous, and a compilation error will result </li></ul></ul></ul><ul><ul><li>See ex20.java </li></ul></ul><ul><ul><li>Note: This type of polymorphism is not necessarily object-oriented – can be done in non-object-oriented languages </li></ul></ul>
    53. 53. Polymorphism <ul><li>Subclassing Polymorphism </li></ul><ul><ul><li>Sometimes called “true polymorphism” </li></ul></ul><ul><ul><li>Consists basically of two ideas: </li></ul></ul><ul><ul><li>Method overriding </li></ul></ul><ul><ul><ul><li>A method defined in a superclass is redefined in a subclass with an identical method signature </li></ul></ul></ul><ul><ul><ul><li>Since the signatures are identical, rather than overloading the method, it is instead overriding the method </li></ul></ul></ul><ul><ul><ul><ul><li>For subclass objects, the definition in the subclass replaces the version in the superclass </li></ul></ul></ul></ul>
    54. 54. Polymorphism <ul><ul><li>Dynamic (or late) binding </li></ul></ul><ul><ul><ul><li>The code executed for a method call is associated with the call during run-time </li></ul></ul></ul><ul><ul><ul><li>The actual method executed is determined by the type of the object , not the type of the reference </li></ul></ul></ul><ul><ul><li>Allows superclass and subclass objects to be accessed in a regular, consistent way </li></ul></ul><ul><ul><ul><li>Array or collection of superclass references can be used to access a mixture of superclass and subclass objects </li></ul></ul></ul><ul><ul><ul><li>This is very useful if we want access collections of mixed data types (ex: draw different graphical objects using the same draw() method call for each) </li></ul></ul></ul>
    55. 55. Polymorphism <ul><li>Ex. Each subclass overrides the move() method in its own way </li></ul><ul><li>Animal [] A = new Animal[3]; </li></ul><ul><li>A[0] = new Bird(); </li></ul><ul><li>A[1] = new Person(); </li></ul><ul><li>A[2] = new Fish(); </li></ul><ul><li>for (int i = 0; i < A.length; i++) </li></ul><ul><li>A[i].move(); </li></ul>Animal move() move() move() <ul><li>References are all the same, but objects are not </li></ul><ul><li>Method invoked is that associated with the OBJECT, NOT with the reference </li></ul>
    56. 56. Object, Method and Instance Variable Access <ul><li>When mixing objects of difference classes, some access rules are important to know: </li></ul><ul><ul><li>Superclass references can always be used to access subclass objects , but NOT vice versa </li></ul></ul><ul><ul><ul><li>Animal A = new Bird(); // this is ok </li></ul></ul></ul><ul><ul><ul><li>Bird B = new Animal(); // this is an ERROR </li></ul></ul></ul><ul><ul><li>Given a reference R of class C , only methods and instance variables that are defined (initially) in class C or ABOVE in the class hierarchy can be accessed through R </li></ul></ul><ul><ul><ul><li>They still exist if defined in a subclass, but they are not accessible through R </li></ul></ul></ul>
    57. 57. Object, Method and Instance Variable Access <ul><ul><li>Ex: </li></ul></ul><ul><ul><ul><li>Suppose class Fish contains a new instance variable waterType and a new method getWaterType() </li></ul></ul></ul><ul><ul><ul><ul><li>Fish F = new Fish(); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Animal A = new Fish(); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(F.getWaterType()); // ok </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(A.getWaterType()); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>The above is NOT legal, even though the method exists for class Fish. The reason is that the method is not visible from the reference’s point of view (A is an Animal reference so it can only “see” the data and methods defined in class Animal) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(((Fish) A).getWaterType()); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>This is ok, since we have now cast the reference to the Fish type, which CAN access the method </li></ul></ul></ul></ul>
    58. 58. Object, Method and Instance Variable Access <ul><ul><ul><li>Note that we can access these methods or instance variables INDIRECTLY if an overridden method accesses them </li></ul></ul></ul><ul><ul><ul><ul><li>So, for example, if the move() method as defined in class Fish called the getWaterType() method, and we called </li></ul></ul></ul></ul><ul><ul><ul><ul><li>A.move(); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>It would work fine </li></ul></ul></ul></ul><ul><ul><ul><ul><li>See ex21.java for an example </li></ul></ul></ul></ul>
    59. 59. Object Methods <ul><li>We’ve already seen that every class automatically inherits from Object </li></ul><ul><li>Class Object defines a set of methods that every class inherits </li></ul><ul><ul><li>public String toString() </li></ul></ul><ul><ul><li>public boolean equals() </li></ul></ul><ul><ul><li>public int hashCode() </li></ul></ul><ul><ul><li>protected Object clone() //we’ll ignore this </li></ul></ul><ul><li>Each of these forms a contract to which all objects must adhere </li></ul><ul><li>Object has a default implementation for each of these methods </li></ul><ul><ul><li>Unless our classes override them, they inherit this behavior </li></ul></ul><ul><ul><li>May or may not be what our classes require </li></ul></ul>
    60. 60. toString() <ul><li>toString() returns a string representation of the object </li></ul><ul><li>The string “should be a concise but informative representation that is easy for a person to read </li></ul><ul><li>RULE: All classes should override this method </li></ul><ul><li>Default implementation from the Object class constructs a string like: </li></ul><ul><ul><li>[email_address] </li></ul></ul><ul><ul><li>Name of the class, ‘@’ character, followed by the HashCode for the class </li></ul></ul>
    61. 61. equals() <ul><li>Indicates whether two objects are logically equal to each other </li></ul><ul><ul><li>Ex. string1.equals(“done”) </li></ul></ul><ul><li>Seems simple, but there is some subtlety here </li></ul><ul><li>equals() must satisfy the definition of an “equivalence relation” </li></ul><ul><ul><li>Reflexive </li></ul></ul><ul><ul><li>Symmetric </li></ul></ul><ul><ul><li>Transitive </li></ul></ul><ul><li>Default implementation from the Object class is equivalent to ‘==‘ </li></ul><ul><ul><li>For any two references, x and y: </li></ul></ul><ul><ul><ul><li>x.equals(y) is true if and only if x == y </li></ul></ul></ul><ul><ul><li>The references must point to the same object for equals() to return true </li></ul></ul>
    62. 62. Contract of equals() <ul><li>equals() must be: </li></ul><ul><ul><li>Reflexive : for any non-null reference variable, x: </li></ul></ul><ul><ul><ul><ul><li>x.equals(x) must be true </li></ul></ul></ul></ul><ul><ul><li>Symmetric : for any two non-null reference variables, x and y: </li></ul></ul><ul><ul><ul><li>If x.equals(y) is true , then y.equals(x) must be true </li></ul></ul></ul><ul><ul><li>Transitive : for any non-null reference variables, x, y, and z: </li></ul></ul><ul><ul><ul><li>If x.equals(y) is true and y.equals(z) is true , then x.equals(z) must be true </li></ul></ul></ul><ul><ul><li>Consistent : for any two non-null references, x and y, mutliple calls to x.equals(y) must consistently return true or consistently return false unless the data stored in either x or y changes between calls to equals() . </li></ul></ul><ul><ul><li>Safe : for non-null reference x and null reference y: </li></ul></ul><ul><ul><ul><li>x.equals(y) must return false </li></ul></ul></ul><ul><ul><ul><li>i.e. x.equals(null) must return false </li></ul></ul></ul><ul><ul><ul><li>equals() should not generate a NullPointerException , or ClassCastException </li></ul></ul></ul>
    63. 63. Contract of equals() <ul><li>Consider a class SubClass </li></ul><ul><ul><li>Extends SuperClass </li></ul></ul><ul><li>Has the following equals() method </li></ul><ul><ul><li>public boolean equals(Object o) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>SubClass sub = (SubClass) o; </li></ul></ul><ul><ul><li>return (name.equals(sub.name) && type.equals(sub.type)); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>What’s wrong with this? </li></ul><ul><ul><li>Object o could be null </li></ul></ul><ul><ul><li>Need to check </li></ul></ul><ul><ul><li>i f(o == null) return false; </li></ul></ul>
    64. 64. Contract of equals() <ul><li>Now consider the super class, SuperClass </li></ul><ul><ul><li>Has it’s own equals method </li></ul></ul><ul><ul><li>public boolean equals(Object o) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>if(o == null) return false; </li></ul></ul><ul><ul><li>SuperClass sup = (SuperClass) o; </li></ul></ul><ul><ul><li>return name.equals(sup.name); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>What’s wrong here? </li></ul><ul><ul><li>Object o may be an instance of SubClass </li></ul></ul><ul><ul><li>The cast will succeed, though, since SubClass extends SuperClass </li></ul></ul><ul><ul><li>What about symmetry: o.equals(this) won’t return true </li></ul></ul><ul><ul><ul><li>ClassCastException will result </li></ul></ul></ul><ul><ul><li>In general, an instance cannot be equal to any instance of a subclass </li></ul></ul><ul><ul><ul><li>This may be desirable in some cases </li></ul></ul></ul><ul><ul><ul><li>Extremely difficult to maintain a working ‘contract of equals()’ </li></ul></ul></ul>
    65. 65. Template for equals() <ul><li>For any class, the general form of the equals() method should be: </li></ul><ul><ul><li>public class MyClass </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>public boolean equals(Object o) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> if(o == null) return false; </li></ul></ul><ul><ul><li> if(o instanceof MyClass) </li></ul></ul><ul><ul><li> { </li></ul></ul><ul><ul><li> MyClass my = (MyClass) o; </li></ul></ul><ul><ul><li> //perform comparison </li></ul></ul><ul><ul><li> } </li></ul></ul><ul><ul><li> return false; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>
    66. 66. hashCode() <ul><li>Returns a integer index value for the object </li></ul><ul><ul><li>Used by hashtables to store objects </li></ul></ul><ul><li>Contract </li></ul><ul><ul><li>Multiple calls to hashCode() during one execution of the program must return the same integer </li></ul></ul><ul><ul><ul><li>Assuming no data contained in the object changes between calls </li></ul></ul></ul><ul><ul><li>For any two non-null references, x and y: </li></ul></ul><ul><ul><ul><li>If x.equals(y), then x.hashCode() == y.hashCode() </li></ul></ul></ul><ul><ul><ul><li>If they are logically equal, they must have the same hashCode() </li></ul></ul></ul><ul><ul><ul><li>If they aren’t equal, it doesn’t matter what the hashCode() returns </li></ul></ul></ul>
    67. 67. Composition or Inheritance <ul><li>Caveats like those we just discussed arise often with Inheritance </li></ul><ul><li>Also, In heritance permanently associates a superclass with our class at compile time </li></ul><ul><ul><li>We can only inherit from a single class </li></ul></ul><ul><ul><li>Composition allows our class the flexibility to wrap around different superclasses at run-time </li></ul></ul><ul><li>Composition is generally preferred over Inheritance </li></ul><ul><li>We loose polymorphism and dynamic binding with Composition though </li></ul><ul><ul><li>In many cases, we need those capabilities </li></ul></ul><ul><ul><li>We use abstract classes and Interfaces to help solve these problems </li></ul></ul>
    68. 68. Exceptions in Java <ul><li>Run-time errors happen </li></ul><ul><ul><li>User enters incorrect input </li></ul></ul><ul><ul><li>Resource is not available (ex. file) </li></ul></ul><ul><ul><li>Logic error (bug) that was not fixed </li></ul></ul><ul><li>For Production software </li></ul><ul><ul><li>Having a program &quot;crash&quot; is a HIGHLY UNDESIRABLE thing </li></ul></ul><ul><ul><ul><li>Users think software is no good </li></ul></ul></ul><ul><ul><ul><li>Lose confidence </li></ul></ul></ul>
    69. 69. Exceptions in Java <ul><li>Exception: </li></ul><ul><ul><li>An occurrence of an erroneous, unusual or unexpected event in a program execution </li></ul></ul><ul><ul><li>In older languages </li></ul></ul><ul><ul><ul><li>Code the handling of exceptions into each area of the program that needed it </li></ul></ul></ul><ul><ul><ul><li>Some exceptions could not even be handled by the HLL </li></ul></ul></ul><ul><ul><ul><ul><li>ex. standard Pascal cannot handle I/O errors or division by 0 </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Ask for integer and user enters a text string – what do you do? </li></ul></ul></ul></ul></ul>
    70. 70. Exceptions in Java <ul><ul><li>In newer languages </li></ul></ul><ul><ul><ul><li>Exception handling built into the language </li></ul></ul></ul><ul><ul><ul><li>We can separate exception handling from the &quot;main line&quot; code </li></ul></ul></ul><ul><ul><li>Java uses an exception handling model similar to that used in C++ </li></ul></ul>Exceptions are objects that are throw n and catch ed Some exceptions are built into the language Others can be created and thrown by the programmer
    71. 71. Exceptions in Java <ul><li>Java exception handling </li></ul><ul><ul><li>Exceptions are handled using try-catch blocks </li></ul></ul>try { // code that will normally execute } catch (ExceptionType1 e) { // code to &quot;handle&quot; this exception } catch (ExceptionType2 e) { // code to &quot;handle&quot; this exception } ... // can have many catches finally { // code to &quot;clean up&quot; before leaving try block }
    72. 72. Exceptions in Java <ul><ul><li>If all goes well (no exceptions occur) </li></ul></ul><ul><ul><ul><li>Code in try block is executed, followed by code in (optional) finally block </li></ul></ul></ul><ul><ul><li>If an exception occurs anywhere in the try block </li></ul></ul><ul><ul><ul><li>Execution immediately jumps out of the try block </li></ul></ul></ul><ul><ul><ul><li>An exception handler is sought in a catch block </li></ul></ul></ul><ul><ul><ul><li>If exception is handled in a catch block, that block executes; if not, exception is propagated </li></ul></ul></ul><ul><ul><li>Whether exception is handled or propagated, finally block is executed </li></ul></ul>
    73. 73. Exceptions in Java <ul><ul><li>If an exception is handled </li></ul></ul><ul><ul><ul><li>Execution resumes immediately AFTER try/catch block in which it was handled , and does NOT return to throw point </li></ul></ul></ul><ul><ul><ul><li>termination model of exception handling </li></ul></ul></ul><ul><ul><ul><ul><li>As opposed to a resumption model, where execution resumes from where the exception occurred </li></ul></ul></ul></ul><ul><ul><li>If an exception is propagated </li></ul></ul><ul><ul><ul><li>A handler is searched for by backing up through the call chain on the run-time stack </li></ul></ul></ul><ul><ul><ul><li>This is dynamic exception propagation </li></ul></ul></ul><ul><ul><ul><li>If no handler is ever found </li></ul></ul></ul><ul><ul><ul><ul><li>Console applications crash and report exception </li></ul></ul></ul></ul><ul><ul><ul><ul><li>GUI applications will continue to execute, but may be in an inconsistent state – more soon </li></ul></ul></ul></ul>
    74. 74. Exceptions in Java <ul><li>Checked vs. Unchecked exceptions </li></ul><ul><ul><li>Checked exceptions </li></ul></ul><ul><ul><ul><li>If a method does NOT handle these, the method MUST state that it throws them </li></ul></ul></ul><ul><ul><ul><ul><li>Done in a throws clause in the method header </li></ul></ul></ul></ul><ul><ul><ul><li>These include IOException, and InterruptedException (and their subclasses) </li></ul></ul></ul><ul><ul><li>Unchecked exceptions </li></ul></ul><ul><ul><ul><li>Method not required to explicitly &quot;throw&quot; these </li></ul></ul></ul><ul><ul><ul><li>These include RunTimeException and Error </li></ul></ul></ul>
    75. 75. Exceptions in Java <ul><li>Catching exceptions </li></ul><ul><ul><li>Catching a superclass of an exception will catch subclass exception objects </li></ul></ul><ul><ul><ul><ul><li>catch (Exception e) </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>&quot;catch all&quot; if no other exceptions match </li></ul></ul></ul></ul></ul><ul><ul><li>Should list exceptions in order of most specific to most general </li></ul></ul><ul><ul><ul><ul><li>If catch above is first NO OTHER catches in the block could ever execute </li></ul></ul></ul></ul><ul><ul><li>It is better style to be as specific as possible with the exceptions that are caught </li></ul></ul><ul><ul><ul><li>See ex22.java </li></ul></ul></ul>
    76. 76. Abstract Classes <ul><li>Abstract classes </li></ul><ul><ul><li>Sometimes in a class hierarchy, a class may be defined simply to give cohesion to its subclasses </li></ul></ul><ul><ul><ul><li>No objects of that class will ever be defined </li></ul></ul></ul><ul><ul><ul><li>But instance data and methods will still be inherited by all subclasses </li></ul></ul></ul><ul><ul><li>This is an abstract class </li></ul></ul><ul><ul><ul><li>Keyword abstract used in declaration </li></ul></ul></ul><ul><ul><ul><li>One or more methods declared to be abstract and are thus not implemented </li></ul></ul></ul><ul><ul><ul><li>No objects may be instantiated </li></ul></ul></ul>
    77. 77. Abstract Classes <ul><ul><li>Subclasses of an abstract class must implement all abstract methods, or they too must be declared to be abstract </li></ul></ul><ul><ul><li>Advantages </li></ul></ul><ul><ul><ul><li>Can still use superclass reference to access all subclass objects in polymorphic way </li></ul></ul></ul><ul><ul><ul><ul><li>However, we need to declare the methods we will need in the superclass, even if they are abstract </li></ul></ul></ul></ul><ul><ul><ul><li>No need to specifically define common data and methods for each subclass - it is inherited </li></ul></ul></ul><ul><ul><ul><li>Helps to organize class hierarchy </li></ul></ul></ul><ul><ul><li>See ex23.java </li></ul></ul><ul><ul><li>Let’s look at MusicCD and CompilationCD again too </li></ul></ul>
    78. 78. Interfaces <ul><li>Java allows only single inheritance </li></ul><ul><ul><li>A new class can be a subclass of only one parent (super) class </li></ul></ul><ul><ul><li>There are several reasons for this, from both the implementation (i.e. how to do it in the compiler and interpreter) point of view and the programmer (i.e. how to use it effectively) point of view </li></ul></ul><ul><ul><li>However, it is sometimes useful to be able to access an object through more than one superclass reference </li></ul></ul>
    79. 79. Interfaces <ul><ul><li>We may want to identify an object in multiple ways: </li></ul></ul><ul><ul><ul><li>One based on its inherent nature (i.e. its inheritance chain) </li></ul></ul></ul><ul><ul><ul><ul><li>Ex: A Person </li></ul></ul></ul></ul><ul><ul><ul><li>Others based on what it is capable of doing </li></ul></ul></ul><ul><ul><ul><ul><li>Ex: An athlete </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Ex: a pilot </li></ul></ul></ul></ul>
    80. 80. Interfaces <ul><li>A Java interface is a named set of methods </li></ul><ul><ul><ul><li>However, no method bodies are given – just the headers </li></ul></ul></ul><ul><ul><ul><li>Static constants are allowed, but no instance variables are allowed </li></ul></ul></ul><ul><ul><ul><li>No static methods are allowed </li></ul></ul></ul><ul><ul><li>Any Java class (no matter what its inheritance) can implement an interface by implementing the methods defined in it </li></ul></ul><ul><ul><li>A given class can implement any number of interfaces </li></ul></ul>
    81. 81. Interfaces <ul><ul><li>Ex: </li></ul></ul><ul><ul><ul><li>public interface Laughable </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li> public void laugh(); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>public interface Booable </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li> public void boo(); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>Any Java class can implement Laughable by implementing the method laugh() </li></ul></ul></ul><ul><ul><ul><li>Any Java class can implement Booable by implementing the method boo() </li></ul></ul></ul>
    82. 82. Interfaces <ul><li>Ex: </li></ul><ul><ul><ul><li>public class Comedian implements Laughable, Booable </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li> // various methods here (constructor, etc.) </li></ul></ul></ul><ul><ul><ul><li> public void laugh() </li></ul></ul></ul><ul><ul><ul><li> { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“Ha ha ha”); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li> public void boo() </li></ul></ul></ul><ul><ul><ul><li> { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“You stink!”); </li></ul></ul></ul><ul><ul><ul><li> } </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
    83. 83. Interfaces <ul><ul><li>An interface variable can be used to reference any object that implements that interface </li></ul></ul><ul><ul><ul><li>Note that the same method name (ex: laugh() below) may in fact represent different code segments in different classes </li></ul></ul></ul><ul><ul><ul><li>Also, only the interface methods are accessible through the interface reference </li></ul></ul></ul><ul><ul><li>Ex: </li></ul></ul><ul><ul><ul><li>Laughable L1, L2, L3; </li></ul></ul></ul><ul><ul><ul><li>L1 = new Comedian(); </li></ul></ul></ul><ul><ul><ul><li>L2 = new SitCom(); // implements Laughable </li></ul></ul></ul><ul><ul><ul><li>L3 = new Clown(); // implements Laughable </li></ul></ul></ul><ul><ul><ul><li>L1.laugh(); L2.laugh(); L3.laugh(); </li></ul></ul></ul>
    84. 84. Interfaces <ul><ul><li>Polymorphism and Dynamic Binding also apply to interfaces </li></ul></ul><ul><ul><ul><li>the interface acts as a superclass and the implementing classes implement the actual methods however they want </li></ul></ul></ul><ul><ul><li>An interface variable can be used to reference any object that implements that interface </li></ul></ul><ul><ul><ul><li>However, only the interface methods are accessible through the interface reference </li></ul></ul></ul><ul><ul><li>Recall our previous example: </li></ul></ul><ul><ul><ul><li>Laughable [] funny = new Laughable[3]; </li></ul></ul></ul><ul><ul><ul><li>funny[0] = new Comedian(); </li></ul></ul></ul><ul><ul><ul><li>funny[1] = new SitCom(); // implements Laughable </li></ul></ul></ul><ul><ul><ul><li>funny[2] = new Clown(); // implements Laughable </li></ul></ul></ul><ul><ul><ul><li>for (int i = 0; i < funny.length; i++) </li></ul></ul></ul><ul><ul><ul><li> funny[i].laugh(); </li></ul></ul></ul><ul><ul><li>See ex24.java </li></ul></ul>
    85. 85. &quot;Generic&quot; Operations <ul><ul><li>How does it benefit us to be able to access objects through interfaces? </li></ul></ul><ul><ul><ul><li>Sometimes we are only concerned about a given property or behavior of a class </li></ul></ul></ul><ul><ul><ul><ul><li>The other attributes and methods still exist, but we don't care about them for what we want to do </li></ul></ul></ul></ul><ul><ul><ul><li>For example: Sorting </li></ul></ul></ul><ul><ul><ul><ul><li>We can sort a lot of different types of objects </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Various numbers </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>People based on their names alphabetically </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Movies based on their titles </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Employees based on their salaries </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>Each of these classes can be very different </li></ul></ul></ul></ul><ul><ul><ul><ul><li>However, something about them all allows them to be sorted </li></ul></ul></ul></ul>
    86. 86. “Generic” Operations <ul><ul><li>They all can be compared to each other </li></ul></ul><ul><ul><ul><li>So we need some method that invokes this comparison </li></ul></ul></ul><ul><ul><li>In order to sort them, we don't need to know or access anything else about any of the classes </li></ul></ul><ul><ul><ul><li>Thus, if they all implement an interface that defines the comparison, we can sort them all with a single method that is defined in terms of that interface </li></ul></ul></ul><ul><ul><li>Huh? Qué? </li></ul></ul><ul><ul><ul><li>Perhaps it will make more sense if we develop an example…but first we will need some background! </li></ul></ul></ul>
    87. 87. Simple Sorting <ul><li>What does it mean to sort our data? </li></ul><ul><ul><li>Consider an array, A of N items: </li></ul></ul><ul><ul><li>A[0], A[1], A[2], …, A[N-1] </li></ul></ul><ul><ul><li>A is sorted in ascending order if </li></ul></ul><ul><ul><li>A[i] < A[j] for all i < j </li></ul></ul><ul><ul><li>A is sorted in descending order if </li></ul></ul><ul><ul><li>A[i] > A[j] for all i < j </li></ul></ul><ul><ul><li>Q: What if we want non-decreasing or non-increasing order? </li></ul></ul><ul><ul><ul><li>What does it mean and how do we change the definitions? </li></ul></ul></ul>
    88. 88. Simple Sorting <ul><li>How do we sort? </li></ul><ul><ul><li>There are MANY ways of sorting data </li></ul></ul><ul><ul><ul><li>Sorting has been widely studied in computer science </li></ul></ul></ul><ul><ul><li>Some algorithms are better than others </li></ul></ul><ul><ul><ul><li>The most useful measure of “better” here is how long it takes to run </li></ul></ul></ul><ul><ul><ul><li>The better algorithms run a lot more quickly than the poorer algorithms </li></ul></ul></ul><ul><ul><li>However, some very simple algorithms are ok if N is not too large </li></ul></ul><ul><ul><ul><li>We will look at a simple algorithm here </li></ul></ul></ul><ul><ul><ul><ul><li>In CS 0445 you will see other, better ways of sorting </li></ul></ul></ul></ul>
    89. 89. SelectionSort <ul><li>SelectionSort is very intuitive: </li></ul><ul><ul><li>Idea: </li></ul></ul><ul><ul><ul><li>Find the smallest item and swap it into index 0 </li></ul></ul></ul><ul><ul><ul><li>Find the next smallest item and swap it into index 1 </li></ul></ul></ul><ul><ul><ul><li>Find the next smallest item and swap it into index 2 </li></ul></ul></ul><ul><ul><ul><li>… </li></ul></ul></ul><ul><ul><ul><li>Find the next smallest item and swap it into index N-2 </li></ul></ul></ul><ul><ul><ul><li>What about index N-1? </li></ul></ul></ul><ul><ul><li>Let’s trace it on the board for the following data: </li></ul></ul>60 15 10 75 40 20 50 35 7 6 5 4 3 2 1 0
    90. 90. SelectionSort <ul><ul><li>Let’s look at the code </li></ul></ul><ul><ul><ul><li>SortInt.java and ex25.java </li></ul></ul></ul><ul><ul><ul><li>Note: </li></ul></ul></ul><ul><ul><ul><ul><li>Done in a modular way utilizing methods </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Trace it on the example from previous slide </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Done here in terms of only one type – int </li></ul></ul></ul></ul><ul><ul><ul><li>So how can we sort arrays of other types, for example objects? </li></ul></ul></ul><ul><ul><ul><ul><li>We could write a version of SelectionSort for each </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Lots of typing, where everything other than the types involved is the same for each one </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Is there a better way? </li></ul></ul></ul></ul>
    91. 91. Comparable Interface <ul><ul><li>Consider the Comparable interface: </li></ul></ul><ul><ul><ul><li>It contains one method: </li></ul></ul></ul><ul><ul><ul><li>int compareTo(Object r); </li></ul></ul></ul><ul><ul><ul><li>Returns a negative number if the current object is less than r, 0 if the current object equals r and a positive number if the current object is greater than r </li></ul></ul></ul><ul><ul><ul><li>Look at Comparable in the API </li></ul></ul></ul><ul><ul><ul><li>Not has restrictive as equals() – can throw ClassCastException </li></ul></ul></ul><ul><ul><li>Consider what we need to know to sort data: </li></ul></ul><ul><ul><ul><li>is A[i] less than, equal to or greater than A[j] </li></ul></ul></ul><ul><ul><li>Thus, we can sort Comparable data without knowing anything else about it </li></ul></ul><ul><ul><ul><li>Awesome! </li></ul></ul></ul><ul><ul><ul><li>Polymorphism allows this to work </li></ul></ul></ul>
    92. 92. Using Comparable <ul><ul><li>Think of the objects we want to sort as “black boxes” </li></ul></ul><ul><ul><ul><li>We know we can compare them because they implement Comparable </li></ul></ul></ul><ul><ul><ul><li>We don’t know (or need to know) anything else about them </li></ul></ul></ul><ul><ul><li>Thus, a single sort method will work for an array of any Comparable class </li></ul></ul><ul><ul><ul><li>Let’s write it now, altering the code we already know from our simple sort method </li></ul></ul></ul><ul><ul><ul><li>See Sorting.java and ex26.java </li></ul></ul></ul><ul><ul><ul><ul><li>Also see SortingT.java and ex26T.java </li></ul></ul></ul></ul>
    93. 93. Binary Search <ul><li>Consider Sequential Search again </li></ul><ul><ul><ul><ul><li>See Procedural Programming slides and ex8.java </li></ul></ul></ul></ul><ul><ul><li>Note that in the worst case we look at every item in the array </li></ul></ul><ul><ul><ul><li>We say this is a linear run-time – or time proportional to N, the number of items in the array </li></ul></ul></ul><ul><ul><li>Can we do better? </li></ul></ul><ul><ul><ul><li>If the data is unsorted, no </li></ul></ul></ul><ul><ul><ul><ul><li>It could be any item, so in the worst case we’ll have to try them all </li></ul></ul></ul></ul><ul><ul><ul><li>What if we sort the data? Will that help? </li></ul></ul></ul><ul><ul><li>Consider example: Guess number from 1-1000 </li></ul></ul>
    94. 94. Binary Search <ul><li>Idea of Binary Search : </li></ul><ul><ul><li>Searching for a given key, K </li></ul></ul><ul><ul><li>Guess middle item, A[mid] in array </li></ul></ul><ul><ul><ul><li>If A[mid] == K, we found it and are done </li></ul></ul></ul><ul><ul><ul><li>If A[mid] < K then K must be on right side of the array </li></ul></ul></ul><ul><ul><ul><li>If A[mid] > K then K must be on left side of the array </li></ul></ul></ul><ul><ul><ul><ul><li>Either way, we eliminate ~1/2 of the remaining items with one guess </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Search for 40 below </li></ul></ul></ul></ul>75 60 50 40 35 20 15 10 7 6 5 4 3 2 1 0
    95. 95. Binary Search <ul><ul><ul><li>What if item is not in array? We need a stopping condition in the “not found” case </li></ul></ul></ul><ul><ul><li>Think about what is happening with each test </li></ul></ul><ul><ul><ul><li>Either we move left index to the right or </li></ul></ul></ul><ul><ul><ul><li>We move right index to the left </li></ul></ul></ul><ul><ul><ul><li>Eventually they will “cross” – in this case the item is not found </li></ul></ul></ul><ul><ul><ul><ul><li>Idea is there is “nothing left” in the array to search </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Search previous array for 25 </li></ul></ul></ul></ul><ul><ul><li>How to code this? Not difficult! </li></ul></ul><ul><ul><ul><li>See author's code: Searching.java, PhoneList2.java </li></ul></ul></ul><ul><ul><ul><ul><li>Trace execution </li></ul></ul></ul></ul>
    96. 96. Binary Search <ul><ul><li>So is Binary Search really an improvement over Sequential Search </li></ul></ul><ul><ul><ul><li>Each “guess” removes ~½ of the remaining items </li></ul></ul></ul><ul><ul><ul><li>Thus the total number of guesses cannot exceed the number of times we can cut the array in half until we reach 0 items </li></ul></ul></ul><ul><ul><ul><ul><li>Ex: 32 16 8 4 2 1 => 6 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Generally speaking, for N items in the array, in the worst case we will do ~log 2 N guesses </li></ul></ul></ul></ul><ul><ul><ul><ul><li>This is MUCH better than Sequential Search, which has ~N guesses in the worst case </li></ul></ul></ul></ul><ul><ul><ul><ul><li>You will discuss this more in CS 0445 and CS 1501 </li></ul></ul></ul></ul>
    97. 97. Collections <ul><li>Sorting and Searching are used often </li></ul><ul><li>With Generics, the code only needs written once </li></ul><ul><ul><li>Can then be used in any situation </li></ul></ul><ul><ul><li>Provided we’re dealing with Comparable objects </li></ul></ul><ul><li>Java has predefined these methods for us </li></ul><ul><ul><li>Arrays.sort() </li></ul></ul><ul><ul><li>Arrays.binarySearch() </li></ul></ul><ul><ul><li>Operate on arrays </li></ul></ul><ul><li>There are other ways of storing a group of related objects </li></ul><ul><ul><li>Offer performance benefits over arrays in some situations </li></ul></ul><ul><ul><li>Offer a conceptual implementation of some container </li></ul></ul><ul><ul><ul><li>e.g. a Set </li></ul></ul></ul><ul><ul><ul><ul><li>Doesn’t contain duplicates </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Can Add or Remove objects </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Can perform Union, Intersection, Difference operations </li></ul></ul></ul></ul><ul><ul><ul><ul><li>An object is either in the Set or it isn’t </li></ul></ul></ul></ul>
    98. 98. Collections <ul><li>Java refers to these as “Collections” </li></ul><ul><ul><li>Containers of other data objects </li></ul></ul><ul><ul><li>“ Collect” related objects into a single object </li></ul></ul><ul><li>Provides conceptual view of the container </li></ul><ul><ul><li>Consider a File System for example </li></ul></ul><ul><ul><ul><li>Directory Tree of Files </li></ul></ul></ul><ul><ul><ul><li>Independent of Storage media (Hard Disk, CD, Flash Drive) </li></ul></ul></ul><ul><ul><ul><li>Collections are similar </li></ul></ul></ul><ul><ul><li>Separate Interface with which we access the stored objects from the Implementation </li></ul></ul><ul><li>Used often enough that Java provides standard implementation of each type of Collection </li></ul><ul><ul><li>Collection </li></ul></ul><ul><ul><ul><li>List (Vector) </li></ul></ul></ul><ul><ul><ul><li>Set </li></ul></ul></ul><ul><ul><ul><ul><li>SortedSet </li></ul></ul></ul></ul><ul><ul><ul><li>Queue </li></ul></ul></ul><ul><ul><li>Map (Hashtable) </li></ul></ul><ul><ul><ul><li>SortedMap </li></ul></ul></ul><ul><ul><li>Stack </li></ul></ul><ul><li>See Java API </li></ul>
    99. 99. List <ul><li>What is a List? </li></ul><ul><ul><li>Let’s consider lists we make in every day life </li></ul></ul><ul><ul><li>What kinds are there? </li></ul></ul><ul><ul><li>What information does each store? </li></ul></ul><ul><ul><li>How can we access and change each? </li></ul></ul><ul><li>A List is a sequence of items or objects </li></ul><ul><ul><li>A container of them </li></ul></ul><ul><ul><li>Implied arbitrary order of the elements </li></ul></ul><ul><ul><li>Size shrinks and grows with the number of items in the list </li></ul></ul><ul><ul><li>We can access an element if we know its position in the List </li></ul></ul><ul><ul><li>We can insert an item to any position </li></ul></ul><ul><ul><li>We can remove an item from any position </li></ul></ul>
    100. 100. List Implementation <ul><li>We now have a concept of a List </li></ul><ul><ul><li>A scheme by which we store and access elements in the List </li></ul></ul><ul><ul><li>This is defined by the List Interface in Java </li></ul></ul><ul><ul><ul><li>See Java API </li></ul></ul></ul><ul><ul><ul><li>Notice add(), get(), remove(), contains() </li></ul></ul></ul><ul><ul><ul><li>Assumes objects have well defined equals() method </li></ul></ul></ul><ul><li>This defines the behavior of a List </li></ul><ul><ul><li>In order to use a list, though, we need implement it </li></ul></ul><ul><li>There are two common concrete implementations </li></ul><ul><ul><li>ArrayList </li></ul></ul><ul><ul><ul><li>Uses a private array to store and order the elements </li></ul></ul></ul><ul><ul><li>LinkedList </li></ul></ul><ul><ul><ul><li>Uses a chain of nodes, each of which stores a single item </li></ul></ul></ul><ul><li>When to use each requires knowledge of the implementation </li></ul>
    101. 101. ArrayList <ul><li>We use an array to store the items in the List </li></ul><ul><ul><li>Arrays have a fixed size </li></ul></ul><ul><ul><li>List has an arbitrary size </li></ul></ul><ul><ul><li>If our list has n elements, we need an array of size n or MORE </li></ul></ul><ul><ul><ul><li>We can leave extra empty spaces to store elements added later </li></ul></ul></ul><ul><ul><ul><li>We can resize the array if we need more space </li></ul></ul></ul><ul><li>List needs to maintain an order to the elements </li></ul><ul><ul><li>Array does this for us </li></ul></ul><ul><li>But consider </li></ul><ul><ul><li>Inserting or adding an element </li></ul></ul><ul><ul><ul><li>Need free the index where the element is to be stored </li></ul></ul></ul><ul><ul><ul><li>Need to keep maintain the same order with the new element added </li></ul></ul></ul><ul><ul><ul><li>Requires shifting some elements to higher indices </li></ul></ul></ul><ul><ul><li>Removing an element </li></ul></ul><ul><ul><ul><li>Array now has an unused index </li></ul></ul></ul><ul><ul><ul><li>Have to shift elements to lower indices to keep ordering </li></ul></ul></ul><ul><ul><li>A lot of shifting!!! </li></ul></ul><ul><li>NOTE: The Vector class provides the same implementation, but provides synchronization for multithreaded applications (slower) </li></ul>
    102. 102. LinkedList <ul><li>The strict array indexing causes this need for shifting </li></ul><ul><ul><li>Can we avoid this? </li></ul></ul><ul><li>Consider this class </li></ul><ul><ul><li>public class Node </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>private Object value; </li></ul></ul><ul><ul><li>private Node next; </li></ul></ul><ul><ul><li>… </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>Each Node contains a reference to another Node </li></ul><ul><ul><li>Forms a chain of Nodes </li></ul></ul><ul><li>If we keep a reference to the first Node, we can access any of them by repeatedly accessing the ‘next’ reference </li></ul><ul><ul><li>Show on board </li></ul></ul><ul><ul><li>Getting element at position I requires us to traverse the chain </li></ul></ul><ul><ul><ul><li>Disadvantage over an array </li></ul></ul></ul><ul><li>Consider adding, and removing elements again </li></ul>
    103. 103. Which and How to Use <ul><li>ArrayList when </li></ul><ul><ul><li>Add and remove mostly from end of list </li></ul></ul><ul><ul><li>Perform a lot of additions </li></ul></ul><ul><li>LinkedList when </li></ul><ul><ul><li>Frequent additions and removals at arbitrary positions, especially beginning </li></ul></ul><ul><li>This is discussed further in CS 0445 </li></ul><ul><li>We want to hide the implementation of a collection as much as possible </li></ul><ul><ul><li>We only care that we have List </li></ul></ul><ul><ul><li>List Interface provides this abstraction </li></ul></ul><ul><ul><li>See ex27.java </li></ul></ul>
    104. 104. Set <ul><li>Similar to a List except </li></ul><ul><ul><li>No order to the elements </li></ul></ul><ul><ul><li>Cannot contain duplicate objects </li></ul></ul><ul><li>A Set is a collection of objects that cannot contain duplicates </li></ul><ul><ul><li>No two objects o1 and o2 in a Set can exist such that o1.equals(o2) is true </li></ul></ul><ul><ul><li>Care must be taken when storing mutable objects </li></ul></ul><ul><ul><ul><li>Cannot change data in an object that makes o1.equals(o2) true after they’ve been added to the Set </li></ul></ul></ul><ul><li>Operations on a Set </li></ul><ul><ul><li>Add an element – add() </li></ul></ul><ul><ul><li>Remove an element – remove() </li></ul></ul><ul><ul><li>Test for inclusion – contains() </li></ul></ul><ul><ul><li>Union (combine elements from two Sets) – addAll() </li></ul></ul><ul><ul><li>Intersection (keep elements two Sets have in common) – retainAll() </li></ul></ul><ul><ul><li>Difference (keep elements not found in a second Set) – removeAll() </li></ul></ul><ul><li>Implementations </li></ul><ul><ul><li>HashSet stores elements in a “Hashtable” </li></ul></ul><ul><ul><li>LinkedHashSet : similar to HashSet </li></ul></ul><ul><ul><li>TreeSet stores elements in a Binary Tree </li></ul></ul>
    105. 105. HashSet <ul><li>Imagine implementing a Set with an array </li></ul><ul><ul><li>To maintain the constraint that the Set doesn’t contain duplicates, we’d have to do something like: </li></ul></ul><ul><ul><li>for(int i = 0; i < count; i++) </li></ul></ul><ul><ul><li> if(array[i].equals(newElement)) </li></ul></ul><ul><ul><li>return; //don’t add new element </li></ul></ul><ul><ul><li>array[count++] = newElement; </li></ul></ul><ul><ul><li>We have to check each item before knowing if a duplicate existed in the array </li></ul></ul><ul><li>What if we could know the index where a duplicate would be stored if it was in the Set? </li></ul><ul><ul><li>Just check the element(s) at that index with equals() </li></ul></ul><ul><ul><li>Add the new Element if not there </li></ul></ul><ul><li>This is how a Hashtable works </li></ul><ul><ul><li>Uses newElement.hashCode() to find index </li></ul></ul><ul><li>Notice the need for the contract of equals() and hashCode() </li></ul><ul><ul><li>Why? </li></ul></ul>
    106. 106. Iterators <ul><li>We’ve seen two types of Collection s so far </li></ul><ul><ul><li>List </li></ul></ul><ul><ul><li>Set </li></ul></ul><ul><li>Recall how often we’ve used the following code with arrays </li></ul><ul><ul><li>for(int i = 0; i < array.length; i++) </li></ul></ul><ul><ul><li>{…} </li></ul></ul><ul><ul><li>Loop “for each” element of the array </li></ul></ul><ul><ul><li>Use variable ‘i’ to keep track of position in the array </li></ul></ul><ul><li>This is a common and needed operation for any Collection </li></ul><ul><ul><li>How do we do this when a Collection has no implied order? </li></ul></ul><ul><ul><li>How do we do this in a common way for any type of Collection? </li></ul></ul><ul><li>An Iterator is a object that can traverse over and provide access to each element </li></ul><ul><ul><li>User doesn’t know how it finds the next element </li></ul></ul>
    107. 107. Using Iterators <ul><li>Iterator class defines two methods </li></ul><ul><ul><li>hasNext() </li></ul></ul><ul><ul><ul><li>returns true if there is another element to examine </li></ul></ul></ul><ul><ul><li>next() </li></ul></ul><ul><ul><ul><li>returns the current element as an Object </li></ul></ul></ul><ul><ul><ul><li>Prepares the iterator to return the next element </li></ul></ul></ul><ul><li>Loop then looks like: </li></ul><ul><ul><li>for(Iterator i=collect.iterator(); i.hasNext();) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>MyClass item = (MyClass) i.next(); </li></ul></ul><ul><ul><li>… //Process the item </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>Java provides a shorthand version of this, called “foreach” loop: </li></ul><ul><ul><li>for(Object o : collect) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>MyClass item = (MyClass) o; </li></ul></ul><ul><ul><li>… // Process the item </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>No need to explicitly declare an Iterator </li></ul></ul><ul><ul><li>“ collect” variable must be an instance of a class that implements Iterable interface </li></ul></ul><ul><li>See ex28.java </li></ul>
    108. 108. Order in Sets <ul><li>The HashSet Class is the simplest implementation of the Set interface </li></ul><ul><ul><li>Iterator can return the elements in any particular order </li></ul></ul><ul><ul><li>Can be chaotic </li></ul></ul><ul><li>It can be advantageous to ensure an Iterator returns the elements is some consistent order </li></ul><ul><li>Two implementations of the Set Interface do this </li></ul><ul><ul><li>LinkedHashSet </li></ul></ul><ul><ul><ul><li>Like HashSet </li></ul></ul></ul><ul><ul><ul><li>Iterator returns elements in the order in which they were added to the Set </li></ul></ul></ul><ul><ul><li>TreeSet </li></ul></ul><ul><ul><ul><li>Iterator returns elements in sorted order </li></ul></ul></ul><ul><ul><ul><li>Requires stored objects to be Comparable </li></ul></ul></ul><ul><ul><ul><li>Elements actually stored in sorted order in a binary tree </li></ul></ul></ul><ul><li>See ex28b.java </li></ul>
    109. 109. Queue <ul><li>We often don’t need to be able to modify all a Collection’s elements </li></ul><ul><ul><li>Can even be advantageous to prevent access to every element </li></ul></ul><ul><ul><li>Force modification of the Collection according to specific rules </li></ul></ul><ul><li>A queue is an ordered collection of objects that: </li></ul><ul><ul><li>Allows new items to be added only to the end </li></ul></ul><ul><ul><li>Allows items to be removed only from the front </li></ul></ul><ul><ul><li>Similar to a waiting line </li></ul></ul><ul><ul><li>First item added to the end is the first item removed from the front (FIFO ordering – First In, First Out) </li></ul></ul><ul><ul><li>No other item can be removed until the first item is removed </li></ul></ul><ul><li>Implementation </li></ul><ul><ul><li>How could we implement a Queue? </li></ul></ul><ul><ul><li>An array could impose the needed ordering </li></ul></ul><ul><ul><ul><li>Would require a lot of shifting </li></ul></ul></ul><ul><ul><ul><li>Circular array is still cumbersome </li></ul></ul></ul><ul><ul><li>LinkedList class also implements the Queue interface </li></ul></ul><ul><ul><ul><li>Ideal for a Queue </li></ul></ul></ul><ul><ul><ul><li>Why? </li></ul></ul></ul><ul><li>See ex28c.java </li></ul>
    110. 110. Stack <ul><li>Consider a stack of plates on a spring in a bin in a cafeteria </li></ul><ul><ul><li>When a plate is added, spring compresses, hiding all plates below </li></ul></ul><ul><ul><li>Only plate that can be removed is the top plate </li></ul></ul><ul><ul><ul><li>The last one that was added </li></ul></ul></ul><ul><ul><li>This is the behavior of a Stack </li></ul></ul><ul><li>A Stack is a data structure where objects can only be added to or removed from the top </li></ul><ul><ul><li>Last item added is the first to be removed </li></ul></ul><ul><ul><li>LIFO ordering – Last In, First Out </li></ul></ul>
    111. 111. Stack Implementation <ul><li>How would this best be implemented? </li></ul><ul><ul><li>Array </li></ul></ul><ul><ul><li>Linked list </li></ul></ul><ul><li>Either would be efficient </li></ul><ul><li>Array doesn’t require the extra storage of saving a reference to each object </li></ul><ul><li>java.util.Stack is a concrete class </li></ul><ul><ul><li>Can create instances of it </li></ul></ul><ul><ul><li>Ex: </li></ul></ul><ul><ul><li>Collection collection = new Stack(); </li></ul></ul><ul><ul><li>Stack stack = new Stack(); </li></ul></ul><ul><li>See ex28d.java </li></ul>
    112. 112. Map <ul><li>The Map Interface differs from a Collection </li></ul><ul><li>Defines a mapping from one set of objects to another </li></ul><ul><ul><li>Like a function in Mathematics: y = f(x) </li></ul></ul><ul><ul><li>Given an object, x, the map returns an object, y </li></ul></ul><ul><ul><li>Refer to x as the key </li></ul></ul><ul><li>An array fits this description </li></ul><ul><ul><li>Maps an int to an object stored in the array </li></ul></ul><ul><ul><li>Each int uniquely identifies and is associated with one of the objects </li></ul></ul><ul><li>A Map allows us to impose a logical relationship between an object and its index (key) </li></ul><ul><ul><li>Ex: </li></ul></ul><ul><ul><ul><li>The title a CD could be the index of our AbstractCD class </li></ul></ul></ul><ul><ul><ul><li>A Person’s name could index their phone number (Phone Book) </li></ul></ul></ul>
    113. 113. Map Implementation <ul><li>Recall our discussion of a Set </li></ul><ul><ul><li>Used hashCode() to store object in array </li></ul></ul><ul><ul><li>Used compareTo() to order object in tree </li></ul></ul><ul><li>We now have two objects </li></ul><ul><ul><li>One is the key for other </li></ul></ul><ul><ul><li>Use hashCode() of key to find location to store the other object </li></ul></ul><ul><ul><li>Use compareTo() of key to order second object in a binary tree </li></ul></ul><ul><ul><li>Indexing object then needs to have well defined equals() , hashCode() , and compareTo() </li></ul></ul><ul><ul><li>Stored object doesn’t have to be as strictly implemented </li></ul></ul><ul><li>Analogous Map Implementations to Set </li></ul><ul><ul><li>HashMap </li></ul></ul><ul><ul><li>LinkedHashMap </li></ul></ul><ul><ul><li>TreeMap </li></ul></ul><ul><ul><ul><li>Implements SortedMap Interface </li></ul></ul></ul><ul><li>See ex29.java </li></ul>
    114. 114. Iterating over a Map <ul><li>A Map is a complex data structure </li></ul><ul><ul><li>Keys </li></ul></ul><ul><ul><li>Values </li></ul></ul><ul><li>The keySet() method returns a Set containing all the keys stored in the Map </li></ul><ul><ul><li>Map cannot contain duplicate keys </li></ul></ul><ul><ul><li>Iterate over this Set </li></ul></ul><ul><li>The values() method returns a Collection of all objects that have an associated key </li></ul><ul><ul><li>May contain duplicate objects </li></ul></ul><ul><ul><li>Iterate over this collection </li></ul></ul><ul><li>The entrySet() method returns a Set of all the (key, value) pairs </li></ul><ul><ul><li>Each object in the Set is of the type Map.Entry </li></ul></ul><ul><ul><li>Iterate over this Set </li></ul></ul>
    115. 115. Generics <ul><li>From the previous slides </li></ul><ul><ul><li>Each collection or Iterator returns an Object </li></ul></ul><ul><ul><li>Necessary since it is designed to work for any kind of object </li></ul></ul><ul><ul><li>Requires us to cast the reference to an instance that we need </li></ul></ul><ul><ul><li>Ex: </li></ul></ul><ul><ul><li>List list = new LinkedList(); </li></ul></ul><ul><ul><li>list.add(“Some Pig”); </li></ul></ul><ul><ul><li>String s = (String) list.get(0); </li></ul></ul><ul><ul><li>String t = (String) list.iterator().next(); </li></ul></ul><ul><li>The cast can be annoy </li></ul><ul><li>The list may also not really contain Strings </li></ul><ul><li>We’d like to force the List to only contain specific types </li></ul><ul><ul><li>We wouldn’t need the cast </li></ul></ul><ul><ul><li>We could be sure what type of objects the List contained </li></ul></ul><ul><li>This is where “Generics” works well </li></ul>
    116. 116. Generics <ul><li>We “parameterize” the instance of our List with the type of object we expect it to contain using the <> syntax </li></ul><ul><ul><li>Ex </li></ul></ul><ul><ul><li>List<String> list = new LinkedList<String>(); </li></ul></ul><ul><ul><li>list.add(“Some Pig”); </li></ul></ul><ul><ul><li>String s = list.get(0); </li></ul></ul><ul><ul><li>String t = list.iterator().next(); </li></ul></ul><ul><ul><li>Declares a “List of Strings” instead of a simple List </li></ul></ul><ul><ul><li>Compiler can now ensure only Strings are added to this particular list </li></ul></ul><ul><ul><li>We no longer need the casts </li></ul></ul>
    117. 117. Writing a Generic Class <ul><li>Use the <> syntax in the class defintion </li></ul><ul><li>public interface List<E> </li></ul><ul><li>{ </li></ul><ul><li>void add(E x); </li></ul><ul><li>} </li></ul><ul><li>This is similar to declaring parameters in a method </li></ul><ul><ul><li>Called Formal Type Parameters </li></ul></ul><ul><li>The <E> declares that a type must be used when an instance is created </li></ul><ul><ul><li>The type is then used in place of anywhere the ‘E’ is used in the class definition </li></ul></ul><ul><ul><ul><li>e.g. add(E x); </li></ul></ul></ul>
    118. 118. Subtyping with Generics <ul><li>Consider the following code: </li></ul><ul><li>List<String> listS = new ArrayList<String>(); </li></ul><ul><li>List<Object> listO = listS; </li></ul><ul><li>Is this legal? </li></ul><ul><ul><li>A String is an Object </li></ul></ul><ul><ul><li>A list of Strings is a list of Objects </li></ul></ul><ul><li>What if we call: listO.add(new Object()); </li></ul><ul><ul><li>We’ve added something to the list that isn’t a String </li></ul></ul><ul><ul><li>Compiler thinks it’s a List of Object, though </li></ul></ul><ul><ul><li>Can’t allow assignment statement </li></ul></ul><ul><li>If class Foo extends Bar, List<Foo> is not a List<Bar> </li></ul><ul><ul><li>This is kind of restrictive </li></ul></ul>
    119. 119. Wildcards in Generics <ul><li>Ex: In ex28, we had the method: </li></ul><ul><li>public void printCollection(Collection c) { </li></ul><ul><li>for(Object o : c) </li></ul><ul><li>System.out.println(o); </li></ul><ul><li>} </li></ul><ul><li>To Parameterize this code, we might try: </li></ul><ul><li>public void printCollection(Collection<Object> c) { </li></ul><ul><li>for(Object o : c) </li></ul><ul><li>System.out.println(o); </li></ul><ul><li>} </li></ul><ul><li>With the subtype restriction, we can’t pass anything other than List<Object> </li></ul><ul><ul><li>Not very helpful </li></ul></ul><ul><ul><li>We can handle any type of List, though </li></ul></ul><ul><li>Use Wildcard, ?, in this situation </li></ul>
    120. 120. Wildcards in Generics <ul><li>Ex: </li></ul><ul><li>public void printCollection(Collection<?> c){ </li></ul><ul><li>for(Object o : c) </li></ul><ul><li>System.out.println(o); </li></ul><ul><li>} </li></ul><ul><li>Call this a “Collection of unknown type” </li></ul><ul><ul><li>Any type of Collection can now match this </li></ul></ul><ul><ul><li>Can iterate with type Object </li></ul></ul><ul><ul><ul><li>Any type can be cast to Object – this is safe </li></ul></ul></ul><ul><li>This lets read from the Collection but not modify </li></ul><ul><ul><li>e.g. c.add(new Object()); will fail to compile </li></ul></ul><ul><ul><li>Not sure of the actual type of the Collection </li></ul></ul><ul><li>See ex30.java </li></ul>
    121. 121. Bounded Wildcards <ul><li>Recall our Animal, Fish, Bird, Person classes </li></ul><ul><li>We’d like to write a method like: </li></ul><ul><li>public void printAnimals(Collection<Animal> c) { </li></ul><ul><li>for(Animal a : c) { </li></ul><ul><li>a.characteristics(); </li></ul><ul><li>a.move(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>This can then only accept a Collection of Animal </li></ul><ul><li>If we use a wildcard (‘?’), we lose access to the move() and characteristics() methods </li></ul>
    122. 122. Bounded Wildcards <ul><li>The solution is a bounded wildcard: </li></ul><ul><li>printAnimals(Collection<? extends Animal> c) { </li></ul><ul><li>for(Animal a : c) { </li></ul><ul><li>a.characteristics(); </li></ul><ul><li>a.move(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Stated as a “Collection of any subtype of Animal” </li></ul><ul><ul><li>Can pass a List of Person </li></ul></ul><ul><li>Know that the objects in the Collection are at least Animals </li></ul><ul><ul><li>Iterator can then be a reference to Animal </li></ul></ul><ul><ul><li>Polymorphism will call the appropriate instance method </li></ul></ul><ul><li>Unable to add any new objects to the Collection </li></ul><ul><li>See ex31.java </li></ul>
    123. 123. Bounded Wildcards <ul><li>The ‘ ? extends MyClass ’ syntax defines an upper bound </li></ul><ul><li>Likewise, ‘ ? super MyClass ’ can define a lower bound </li></ul><ul><ul><li>Means any class that is a superclass of class T </li></ul></ul><ul><ul><li>E.g. Comparable<? super T> </li></ul></ul><ul><ul><ul><li>Dealing with a comparable object that can compare itself with any superclass of T </li></ul></ul></ul><ul><li>See next example </li></ul>
    124. 124. Generic Methods <ul><li>Suppose we want to write a method copies an array into a Collection: </li></ul><ul><li>public void fromAtoC(Object[] a, Collection<?> c) { </li></ul><ul><li>for(Object o : a) </li></ul><ul><li>c.add(o);} </li></ul><ul><li>We’ve already learned that we can’t do this with the wildcard </li></ul><ul><li>We can use generic methods </li></ul><ul><li>public <T> void fromAtoC(T[] a, Collection<T> c) { </li></ul><ul><li>for(T o : a) </li></ul><ul><li>c.add(o);} </li></ul><ul><li>All the same wildcard rules apply </li></ul><ul><li>public <T> listCopy(List<? extends T> source, List<T> dest){} </li></ul><ul><li>When to use: </li></ul><ul><ul><li>Notice the dependency between the types in the parameters </li></ul></ul><ul><ul><li>If the dependency does not exist, you should use wildcards instead </li></ul></ul><ul><ul><li>Also used if the return type of the method is type dependent </li></ul></ul><ul><li>See again SortingT.java, ex26T.java, and also ex32 </li></ul>
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×